问题
I want to add a javascript placeholder and place a variable in a jinja template for href place of a link tag . I have tried {% raw %} method and ": method but it seems that the {% raw %} method throws an exception as the following
"% as an unidentified character"
The code is given below, help would be much appreciated or any other method to accomplish the task.
for(i =0 ; i<= channels.length -1;i++){
console.log(channels[i])
const li = document.createElement("li");
li.innerHTML = `<a href = "{{ url_for('channel', channel_name = ${channels[i]}) }}" >${channels[i]}</a>`;
ul.append(li);
};
回答1:
you are mixing things, you can't evaluate javascript variables in jinja2 expression {{ .. }}.
jinja2 renders your template on the server-side and the HTML output is served to the client-side (the browser), whereas the javascipt (your code) manipulates the DOM of the received HTML on the client-side (the browser). so how they would talk to each other ?
you have 3 options:
- using
ajaxto perform http requests (not your case) - reviewing the code and moving the logic to
jinja2(strongly recommended) - or trying this hack:
[..]
let href = "{{ url_for('channel', channel_name='CHANNEL_NAME'} }}".replace("CHANNEL_NAME", ${channels[i])
li.innerHTML = "<a href=" + href + ">${channels[i]}</a>";
[..]
bear in mind that jinja2 will render your template and serve this output:
for(i=0; i<= channels.length-1; i++) {
console.log(channels[i])
const li = document.createElement("li");
let href = "http://localhost:5000/channel/CHANNEL_NAME".replace("CHANNEL_NAME", ${channels[i])
li.innerHTML = "<a href=" + href + ">${channels[i]}</a>";
ul.append(li);
};
and once received by the client, the javascript code can be executed and then process the replacement of the CHANNEL_NAME token with the value of ${channels[i]}
来源:https://stackoverflow.com/questions/62109695/escaping-jinja-template-for-javascript-place-holder