Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The <code>safe</code> filter actually does prevent HTML escaping and thus would provide a solution to your problem.</p> <p>However you get an error in JavaScript because you now have double-quotes inside a string limited by double-quotes!</p> <p>Suppose the value of <code>values[0]</code> is the string: <code>double-quote " and ampersand</code>, you would get:</p> <pre><code>function test() { var nameField=document.getElementById("thing"); nameField.value="double-quote " and ampersand"; //trailing and ampersand causing error } </code></pre> <p>You can be tempted to fix the problem by replacing <code>"{{ values[0] }}"</code> by a single-quote wrapped string <code>'{{ values[0] }}'</code>. But what if your string contains single quotes?</p> <p>You might also think that you will need to escape the special characters, but you would need to use java script escaping (double-quotes become <code>%22</code>) not python escaping (double-quotes become <code>\"</code>).</p> <p>IMHO, the core of your problem lies in the fact that you are using Jinja to print code (not values or mark-up). When you need dynamic behavior, why change the JavaScript code when you can have a static code that provides the dynamic behavior client-side?</p> <p>If <code>values[0]</code> is already in the DOM in your HTML file (in the <code>id</code> of a HTML element, or in any other attribute or in the HTML of an <code>option</code> of a <code>select</code> input), let JavaScript go and fetch it. If it is not in the DOM, put it in a hidden element with an appropriate <code>id</code> e.g. </p> <pre><code>`&lt;div style="diplay:none;" id="value0"&gt;{{ value[0] }}&lt;/div&gt;` </code></pre> <p>and retrieve it when needed.</p> <p>This also has the advantage of decoupling completely your JavaScript code from your server-side page generation and Jinja: your JavaScript would still work under the single condition that the correct HTML structure is provided. You would be able to move the JavaScript to a <code>.js</code> file and use it with other projects, as well as with projects not using Flask/Jinja2.</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.
 

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