python - Jinja2 not rendering quotes or amp in javascript/html; safe filter not solving -
first post; try keep short , sweet.
i trying render edit form detects , populates input fields if values exist fields. i'm using flask jinja2 , when use {{ }} print operator, fields have double quotes , ampersands rendered " , & respectively.
the catch: happens when print operator being used in javascript function. i've looked on solutions, , seemed jinja2 safe filter trick, when appended print value, invalidated of javascript.
below code sample:
function test() { var namefield=document.getelementbyid("thing"); namefield.value="{{ values[0] }}"; } 'values' python list.
please let me know if can add clarify issue.
the safe filter prevent html escaping , provide solution problem.
however error in javascript because have double-quotes inside string limited double-quotes!
suppose value of values[0] string: double-quote " , ampersand, get:
function test() { var namefield=document.getelementbyid("thing"); namefield.value="double-quote " , ampersand"; //trailing , ampersand causing error } you can tempted fix problem replacing "{{ values[0] }}" single-quote wrapped string '{{ values[0] }}'. if string contains single quotes?
you might think need escape special characters, need use java script escaping (double-quotes become %22) not python escaping (double-quotes become \").
imho, core of problem lies in fact using jinja print code (not values or mark-up). when need dynamic behavior, why change javascript code when can have static code provides dynamic behavior client-side?
if values[0] in dom in html file (in id of html element, or in other attribute or in html of option of select input), let javascript go , fetch it. if not in dom, put in hidden element appropriate id e.g.
`<div style="diplay:none;" id="value0">{{ value[0] }}</div>` and retrieve when needed.
this has advantage of decoupling javascript code server-side page generation , jinja: javascript still work under single condition correct html structure provided. able move javascript .js file , use other projects, projects not using flask/jinja2.
Comments
Post a Comment