Search code examples
nunjucks

How to allow HTML to pass through a set block with Nunjucks


I'm really excited to see that we can apply a block assignment for set through Nunjucks. What would be the correct way to allow HTML to be passed through this approach?

I want to do the following from my initial nunjucks file:

{% set demoSetBlock %}
<div class="mClass">
  <p>a header value in a nunjucks set block</p>
</div>
{% endset %}

I then want to call it into my nunjucks template like so...

{{demoSetBlock}}

but...it's printing out the content along with the HTML markup on the web page, just like this...

<div class="mClass"> <p>a header value in a nunjucks set block</p> </div>

How can we render this so that it shows it as...

a header value in a nunjucks set block


Solution

  • Not sure if this is the official way of resolving the situation, but what appears to be working for me now is using |safe as an attribute when the set block is called, like so:

    {{demoSetBlock|safe}}
    

    as a result, my HTML is perfectly rendered on the browser.

    This is helpful in cases

    • when I don't want to depend on macros.
    • when I want to depend on set as an instrumental component for defining and passing data through various parts of my templates.
    • where I have other include files (i.e. _include-header.njk, _include-footer.njk) that are directly attached to my main template file. I could then use set block for one of these files.