Jannis Borgers
Jannis Borgers

Reputation: 41

Twig: Render block multiple times: parsed, escaped, verbatim

I’m building a pattern library that displays my production twig partials with some additional information. Under each pattern, I want to have two code snippets that I want to be generated from my pattern. One is the parsed HTML, the other one is my Twig code directly from the partial file, including variables and other Twig code.

Question

How do I reuse a block that I already parsed and rendered on my page, but in its unparsed form?

Files:

moduleXYZ.html:

{% extends '_pattern.html' %}
{% block pattern %}
  <h2>{{ variable|default('Some placeholder text') }}</h2>
{% endblock %}

_pattern.html:

{% block pattern %}
  No pattern defined.
{% endblock %}
{% use '_pattern-foot.html' %}
{% block('patternfoot') %}

_pattern-foot.html:

{% block patternfoot %}
  <h2>HTML for this pattern:</h2>
  <pre><code>
  {{ block('pattern')|e }} {# THIS WORKS, escaped HTML is displayed. #}
  </code></pre>

  <h2>Twig for this pattern:</h2>
  <pre><code>
  {{ block('pattern')|e }} {# THIS IS NOT WORKING, of course, because the block is already parsed. #}
  </code></pre>

{% endblock %}

What didn’t work

I managed to get the result I want by wrapping the "pattern" block in moduleXYZ.html in {% verbatim %}, but then of course my logic/variables go unparsed in the module itself, too.

I understand it’s not possible to pass variables into the block() function, so I also can’t toggle verbatim conditionally for my reused block (or can I?).

Upvotes: 4

Views: 465

Answers (0)

Related Questions