Escaping jinja template for javascript place holder

寵の児 提交于 2020-07-16 10:19:03

问题


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 &quot: 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 ajax to 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!