Twig: Replace placeholder in string with include

1.6k Views Asked by At

My question is similar to this one: Twig: replace arbitrary token in variable with template include.
I'm hoping things have change since it was asked.

I'm working with twig.js.

I have a server whose task is to listen to requests, receive datas, compile a twig file using those datas and send back the html.
The datas it's receiving is an object containing texts, colors, etc... that are passed as a context to the twig file.

In the data, users can send placeholders like {foo} and I'd like to replace those placeholders with {% include 'partial.twig' %}.

My first try was to use the filter |replace but it doesn't get processed:

{% set foo = foo|replace({'{foo}': '{% include "partial.twig" %}'}) %}

See twigfiddle.

Is there any possibility to extend twig.js to be able to do something like that ?

1

There are 1 best solutions below

1
On BEST ANSWER

You have to do it in two steps, first capture the partial in a variable, then use the variable to replace the placeholder, e.g.

{%- set bar -%}
    {% include "partial.twig" %}
{%- endset -%}

{% set foo = 'this is {foo}' %}

{% set foo = foo|replace({'{foo}': bar }) %}
{{ foo }}

demo

note: {%- ... -%} is used to strip whitespaces