Jinja macros, access to various blocks

I am trying to get a Jinja2 macro to output to another part of the calling template. The reason I want to do this is because embedded Javascript is part of the macro, but I want all Javascript to be at the end of the template. I basically want to do something like this

{% import 'tooltip.html' as tooltip %} 
<html>
  <body>
    {% block contents %}
    {% tooltip('mytool') %}
    {% endblock %}
    <script>
      {% block javascript %}
      {% endblock %}
    </script>
  </body>
</html>

And in the macro file

{% macro tooltip(name) %}
  <div id='{{ name }}'>
    This is my tooltip
  </div>

  {% block javascript %}
  jQuery("#{{ name }}").click(function(){//do something});
  {% endblock %}
{% endmacro %}

So the end result will be similar to

<html>
  <body>
    <div id='mytool'>
      This is my tooltip
    </div>
    <script>
      jQuery("#mytool").click(function(){//do something});
    </script>
  </body>
</html>

I want all my javascript to be at the end of my template, but the macros seem to just go back and forth.

Is there something I am missing, or is it not Jinja2 compliant, and would I need to write an extension?

thank

+3
source share
2 answers

, , Jinja. , :

<div id='mytool'>
  This is my tooltip
</div>

jQuery- ,

<script>
  jQuery("#mytool").click(function(){});
</script>

, class jQuery class. , jQuery , .

- :

<div id="mytool" class="tooltip">
  This is my tooltip
</div>

jQuery:

<script>
  // This will add the onclick handler to any element
  // with a class of "tooltip"
  jQuery(".tooltip").click(function(){});
</script>

jQuery , , , , Jinja.

+4

2 ? , , , , javascript? , . , , " ".

+1

Source: https://habr.com/ru/post/1776259/


All Articles