twigoctobercmsoctobercms-pluginstwig-extensiontwig-filter

Use a twig filter in template_from_string function


I am creating a multilingual website with October CMS, using Rainlab Translate and Vojta Svoboda Twig Extensions plugins. I'm using the twig function template_from_string to create a link button in one of my template files.

Everything works as expected if I use a |media filter in the link attribute, to get the url of a media file. But, if I use a |page filter, to get a page url, I get an error for Unknown "page" filter.

<!-- It works: -->
<div>
    {% set btn = {
        'link': 'foobar.jpg',
        'label': 'Where is FooBar »'
    } %}
    {{ include(template_from_string('<a class="btn btn-promo btn-white move" href="{{ btn.link|media }}" role="button">{{ btn.label }}</a>')) }}
</div>


<!-- It does not work: -->
<div>
    {% set btn = {
        'link': 'foobar',
        'label': 'Where is FooBar »'
    } %}
    {{ include(template_from_string('<a class="btn btn-promo btn-white move" href="{{ btn.link|page }}" role="button">{{ btn.label }}</a>')) }}
</div>

I'm stuck on this problem and my question is: How can I get both filters work? Thank you in advance for your help.


Solution

  • I think you are overlooking stuff :)

    You can use like this

    <div>
        {% set btn = {
            'link': 'fooba'|page, <-- HERE
            'label': 'Where is FooBar »'
        } %}
        {{ include(template_from_string('<a class="btn btn-promo btn-white move" href="{{ btn.link }}" role="button">{{ btn.label }}</a>')) }}
    </div>
    

    you can use filter on main scope and just pass filtered value directly. you do not need to use filters inside template_from_string

    if any doubt please comment.