3

I'm rendering some HTML into a variable. On this HTML I want to replace a value using craft.request.getUrl() but the value doesn't seem to get replaced. Any idea what I'm doing wrong?

{% set pages %}
    {% set entries = craft.entries.section('pages') %}
    {% for entry in entries %}
         <a href="{{ entry.url }}" data-url="{{ entry.url }}">{{ entry.title }}</a>
    {% endfor %}
{% endset %}

{{ pages|replace({'data-url="{{ craft.request.getUrl() }}"': 'class="active"'})|raw }}

1 Answer 1

6

Try:

{{ pages|replace({('data-url="' ~ craft.request.getUrl() ~ '"'): 'class="active"'})|raw }}

You were double nesting Twig tags {{ {{ }} }}, which is never necessary. You'll want to use string concatenation instead. Also for dynamic keys in twig you need parentheses.

3
  • {{ navigation|replace({'data-url="' ~ craft.request.getUrl() ~ '"': 'class="active"'})|raw }} gives me "A hash key must be followed by a colon (:)" and {{ navigation|replace({'data-url="' ~ craft.request.getUrl() ~ "': 'class="active"'})|raw }} gives me error "Unclosed """". Any ideas? Commented Jul 30, 2014 at 7:48
  • @naboovalley for dynamic keys in twig you need parentheses, so try {{ navigation|replace({('data-url="' ~ craft.request.getUrl() ~ '"'): 'class="active"'})|raw }} Commented Jul 30, 2014 at 10:52
  • That did it! :) Commented Jul 30, 2014 at 13:52

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.