What's the right way to have a contextual link on controller action? I just installed a custom module and created a controller with index function in it. I want to have a contextual link for this. I have following code in index function.

public function index() {
    return [
        '#type' =&gt; 'markup',
        '#markup' =&gt; $this-&gt;t('Implement method: hello'),
        '#contextual_links' =&gt; [
            'mymodule' =&gt; 'mymodule.another_action',
        ],
    ];
}


File : mymodule.links.contextual.yml

mymodule_configure:
  title: 'Configure Custom Module'
  route_name: 'mymodule.another_action'
  group: 'my_module'


Please suggest the right way.
I did this using a reference from below.

Adding the contextual link render element

I added a variable to the theme, and passed contextual link in controller function to twig template using that variable. Please see code below.

File : mymodule.module

function mymodule_theme() {
  return [
    'mymodule' =&gt; [
      'template' =&gt; 'mymodule',
      'variables' =&gt; [              //Added a variable content
        'content' =&gt; '',
      ]
    ],
  ];
}


File : mymodule.links.contextual.yml

mymodule_configure:
  title: 'Configure My Module'
  route_name: 'mymodule.route_name'
  group: 'mymodule' 


File : IndexController.php

public function index() {
    $data['content'] = [
        '#type' =&gt; 'markup',
        '#markup' =&gt; $this-&gt;t('Implement method: index'),
    ];

    $data['#contextual_links'] = [
        'mymodule' =&gt; [
            'route_parameters' =&gt; [],
        ],
    ];

    return [
        '#theme' =&gt; 'mymodule',
        '#content' =&gt; $data,        //Pass Contextual link to the variable
    ];
}


File : mymodule.html.twig

{%
set classes = [
'contextual-region'
]
%}

&lt;div {{ attributes.addClass(classes) }}&gt;
  {{ title_prefix }}
  {{ title_suffix }}
  {{ content }}                     //Render here
&lt;/div&gt;


--

Thanks