Skip to content
● Meet Grav Guard: keep every Grav site you run secure and up to date, all from one place. Free for up to 3 sites. Read more →

Twig variable as link

Started by Muut Archive 10 years ago · 8 replies · 3401 views
10 years ago

I stuck at a serious simple problem. I try to loop over Grav pages and dynamically output there links.

TWIG
{% for news in page.find('/aktuelles').children.order('header.news_date', 'asc').slice(0, 3) %}
<div class="recent-news">
    <a href="{{ news.url }}">
    <span>{{ news.header.news_date|date("d.m.Y") }}</span>
    {{ news.title }}
    </a>
</div>
{% endfor %}

Unfortunatly the Twig code

TWIG
{{ news.url }}

doesnt get replaced by the value behind the variable. Instead the generated link looks like this http://127.0.0.1/%7B%7B%20news.url%20%7D%7D. I tested the variable capsuled in the a-Tag. That worked! Does anybody know why twig can´t be rendered in a´s href-Attribute and have a workaround for me? Thanks!

10 years ago

It's strange, it seems that Twig is not parsed. But since you're in the loop, and the title is shown, Twig is processing.

Moving it outside the <a> tag works?

10 years ago

yes, also moving outside the href works. My only actual workaround right now is to write the url in data-href and replace href on DOM load with the value with JS.

10 years ago

Hello,
I don't know why it's not working, but you could try this workaround :
Define a variable :

TWIG
{% set newsLink = news.url %}

Then use the variable instead of news.url :

TWIG

<a href="{{ newsLink }}"></a>
---
10 years ago

Thanks for your nice idea. Also tried it, but also not working. Twig got not parsed in the a´s href.

10 years ago

Oh wow! That is actually working but not a charm for my HTML markup :D

10 years ago

Is there another aproach to fix it on this way?

Suggested topics

Topic Participants Replies Views Activity
Archive · by Muut Archive, 10 years ago
1 672 1 week ago
Archive · by Deleted User, 9 years ago
0 3042 9 years ago
Archive · by Muut Archive, 9 years ago
2 1983 9 years ago
Archive · by Muut Archive, 9 years ago
2 5336 9 years ago
Archive · by Muut Archive, 9 years ago
1 4134 9 years ago