Skip to content Skip to sidebar Skip to footer

Escaping Jinja Template For Javascript Place Holder

I want to pass a javascript variable ${channels[i]} to my jinja2 template as a placeholder for the href attribute of the link tag. I have tried {% raw %}{% endraw %} tags to escap

Solution 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]}

Post a Comment for "Escaping Jinja Template For Javascript Place Holder"