I have a custom block that loads multiple nodes from the database and passes it to the twig template. Inside the template I loop the list printing some node details, but I need to create a link on the node title, possibly its clean (alias) URL. The problem is that with node.url I get a security error:

Twig_Sandbox_SecurityError: "Calling "url" method on a "Drupal\node\Entity\Node" object is not allowed

I tried with {{ link(item.label, item.url.value) }} but I get the same error.

What is the correct way to create a link in twig using the node URL?

  • Use the preprocess function to pass the node URL to the template. Anyway, you don't say how you pass nodes to the template. Also, since the question seem about code, the question would be much more helpful to future users if it shows the code too.
    – apaderno
    Jan 31, 2016 at 10:21
  • You should use preprocessor as mentioned above. Also, I haven tried, but see if maybe {{ attribute(node, 'toUrl') }} works.
    – user21641
    Jan 31, 2016 at 12:21

1 Answer 1


Ok, it seems I have solved the problem using twig/drupal path() function, building the linked title in this way:

<a href="{{ path('entity.node.canonical', {'node': item.id}) }}">{{ item.label }}</a>

where "item" is the node object inside the list loop.


Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.