Search code examples
twiggrav

Grav/Twig get title of twig expression


I want to get the title of a linked page, which is linked by a twig expression.

        <a href="{{ header.home.linkOne }}">#TitleHere</a>

I tried to get the title with page.find but this doesn't work at all. I don’t want to create a backend field to type in the title manually.

Please help me to solve this problem.


Solution

  • We can do this using the twig find() command. I think your problem is that you're trying to find based on the title, and you need to use the path. Luckily Grav gives us the home_url variable which makes this rather simple.

    {% set homepage = page.find(home_url) %}
    <a href="{{ home_url }}">{{ homepage.title }}</a>
    

    I set homepage up as a variable in case you wanted to use it again on the same page. There's no reason to run multiple find()'s if you don't need to. If you aren't going to use it again, you can reduce this to a one liner by removing the first line and replacing homepage.title with page.find(home_url).title.