Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine Python Flask Jinja2 and Mustache

I am using Mustache.js with Flask and jinja2 and have a problem to render images.

I succeeded to render my mustache template in jinja thanks to {% raw %} and {% endraw %} but now I need to use url_for() from Jinja in my template to define my image source. There is a conflict between the {{}} from mustache and the ones from Jinja.

My javascript :

target = document.getElementById("target");
var template = $('#my-template').html();
Mustache.parse(template);
var rendered = Mustache.render(template, {"title":"My Title","photo_name":"photo.jpg"});
target.innerHTML = rendered;

And my template :

<script id="my-template" type="x-tmpl-mustache">
{% raw %}
  <h1> {{title}} </h1>
  <img src="{{ url_for('static',filename='images/{{photo_name}}') }}" alt="my_photo">
{% endraw %}
</script>

Any idea how to solve this problem?

like image 567
F Blanchet Avatar asked Nov 25 '25 21:11

F Blanchet


1 Answers

You are expressing raw treatment over quite a bit of content, some of which you don't really want to be raw. Suggest you narrow the scope of {% raw %} ... {% endraw %} to cover only those template variables you wish Mustache to fill in. For example:

<script id="my-template" type="x-tmpl-mustache">

  <h1> {% raw %}{{title}}{% endraw %} </h1>
  <img src="{{ url_for('static',filename='images/')}}{% raw %}{{photo_name}}{% endraw %}" alt="my_photo">

</script>

To the browser this will render the following, the template sections of which can then be filled in by JS / Mustache:

<script id="my-template" type="x-tmpl-mustache">

  <h1> {{title}} </h1>
  <img src="/static/images/{{photo_name}}" alt="my_photo">

</script>

In this way you get Mustache handling specific template substitutions, Flask / Jinja2 handling the rest.

Using two template engines with such interleaved and overlapping responsibilities—not to mention identical template variable marking syntax—makes the "quoting" entirely essential, yet also very nitsy.

like image 170
Jonathan Eunice Avatar answered Nov 27 '25 09:11

Jonathan Eunice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!