Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy using the "safe" filter in jinja creates nested elements
    primarykey
    data
    text
    <p>I have a python dictionary called "asides". The values of this dict are html snippets loaded from my database and I want to inject them into a jinja template.</p> <p>The below is the jinja snippet:</p> <pre><code>&lt;div class="small-3 large-3 columns"&gt; {% for k in asides.keys() %} &lt;div id={{k}} class="aside"&gt;{{asides[k]|safe}}&lt;/div&gt; {% endfor %} &lt;/div&gt; </code></pre> <p>This creates nested divs. Say my dict has ids 1 and 2, this will do the following:</p> <pre><code>&lt;div class="small-3 large-3 columns"&gt; &lt;div id=1 class="aside"&gt;some html here &lt;div id=2 class="aside"&gt;some html here &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>If I remove the safe filter, it behaves normally creating non nested divs.</p> <p>I would like to know why the safe filter does this and how to avoid it (as I don't want nested divs).</p> <hr> <p>All right, following the suggestion in the comments I realized where the issue was. I am going to document it here as it's a funny business in my opinion.</p> <p>So, in app.py (using Flask):</p> <pre><code>from flask import Flask, render_template app = Flask(__name__) app.debug = True @app.route('/') def index(): d = {'1':'&lt;p&gt;Test 1&lt;/p', '2':'&lt;p&gt;Test 2&lt;/p&gt;'} return render_template('index.html', d=d) if __name__=='__main__': app.run() </code></pre> <p>Note how the html of the first element in d is not correct. The closing p tag is missing a ">".</p> <p>Then in the template</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div&gt; {% for k in d %} &lt;div class={{k}}&gt;{{d[k]|safe}}&lt;/div&gt; {% endfor %} &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>This will nest the second div inside the first div.</p> <p>I think the question is still open as it would be interesting to know why this happens.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload