4

In my module.routing.yml (and using D8), I have a module_new route associated with the /module/name path.

I want to render this path in my module. How can I show http://example.org/module/name on a page?

1 Answer 1

11

Twig

You can use the route name in the twig function url():

<a href="{{ url('module_new') }}">{{ 'View my module content'|t }}</a>

Controller

Or you can do the same in a controller:

use Drupal\Core\Url;

  $url = Url::fromRoute('module_new', [], ['absolute' => TRUE]);

  // get the path as string (not recommended)
  $path = $url->toString;

  // better put the complete url object in a render array and let the template render it
  $build['link'] = [
   '#title' => $this->t('My module content'),
   '#type' => 'link',
   '#url' => $url,
  ];

  return $build;
7
  • How can I use this in my controller handler ?
    – user60258
    Apr 4, 2017 at 6:47
  • I use Url::fromRoute('module_new') but it's not string and not work .
    – user60258
    Apr 4, 2017 at 6:50
  • 1
    :D , I change it to string with ->toString() but not show http :// mysite in string . How can I do this ?
    – user60258
    Apr 4, 2017 at 6:53
  • Not work and not show http:// example .org in my link . I don't want to use $link . I want create http:// example .org/module/name to use in other variables .
    – user60258
    Apr 4, 2017 at 7:11
  • it's better to use the url as object in a render element to build the link, but you can get the path as string, see the edit
    – 4uk4
    Apr 4, 2017 at 7:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.