3

There is a variable {{ author_name }} in node.html.twig, it will print something like below:

<span>Your author name</span>

But I would like to print something like that:

<a href='/user/10'>Your author name</a>

How can I get this done in node.html.twig?

2 Answers 2

5

Normally {{ author_name }} already comes as renderable markup containing the linked author name. But there's also {{ node.getOwnerId }} (the author's user ID) and {{ node.getOwner.label }} (the author's user name) you could simply use to build the link yourself.

<div class="foobar">
  <a href="/user/{{ node.getOwnerId }}">
    <span>{{ node.getOwner.label }}</span>
  </a>
</div>

Note you can easily inspect what variables are available for a template by installing the Devel sub-module Kint and then in your template print {{ kint() }}, flush cache and reload. You now will get all available variables pretty-printed to easily find out which ones you could use to solve your problem.


To make that snippet a little bit more sustainable use the path() function to build the link target. By that also path aliases (built with Pathauto for example) will be taken into account.

<div class="foobar">
  <a href="{{ path('entity.user.canonical', {'user': node.getOwnerId}) }}">
    <span>{{ node.getOwner.label }}</span>
  </a>
</div>
2
  • 2
    Thank you! {{ node.getOwnerId }} and {{ node.getOwner.label }} work well! By the way, {{ node.getOwner.label }} == {{ node.getOwner.getDisplayName }}
    – Basic
    Commented Dec 29, 2018 at 8:30
  • 3
    @Basic, getDisplayName is not identical, it is a processed version of the name/label, see User::getDisplayName
    – 4uk4
    Commented Dec 29, 2018 at 9:26
3

Use {{ node.getOwnerId() }}.

<a href='/user/{{ node.getOwnerId() }}'>Your author name</a>
0

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.