Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

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 }}
share|improve this question

1 Answer 1

up vote 6 down vote accepted

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.

share|improve this answer
    
{{ 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? –  naboovalley Jul 30 at 7:48
    
@naboovalley for dynamic keys in twig you need parentheses, so try {{ navigation|replace({('data-url="' ~ craft.request.getUrl() ~ '"'): 'class="active"'})|raw }} –  Mike Pepper Jul 30 at 10:52
    
That did it! :) –  naboovalley Jul 30 at 13:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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