How to display Jinja2 macro from resolved view?

I have specific macros that are called from multiple templates.

For example, on the Product page there is an Overview section that uses the macros defined in 'helpers/review.jinja2'to print each overview. The file 'helpers/review.jinja2'has two macros:

{% macro render_review(request,review) -%}
{% macro render_review_comment(request,comment) -%}

When someone sends a new review via ajax, I want to return the processed review in order to add content to the Review section.

Now I have an intermediate template 'review/review.jinja2'that looks like this:

{% import 'helpers/review.jinja2' as review_helper %}
{{ review_helper.render_review(request,review) }}

This template is rendered from a view:

@view_config(route_name='review.add_review', renderer='review/review.jinja2')
def add_review(request):
    return dict(review=my_new_review)

But I hope there is a better way to do this. So, is it possible to display the macro defined in the template?

thank

+5
source share
2

get_template_attribute Armin - Flask get_template_attribute (. ). Template Jinja2, , module Template.

, Render Pyramid Jinja2 , , - ( ):

@view_config(route_name='review.add_review',
                renderer='helpers/review.jinja2:render_review')
def add_review(request):
    return dict(review=my_new_review)
+4

, :

@app.route("/test")
def test_view():
    t = app.jinja_env.get_template('macros.html')
    mod = t.make_module({'request': request})
    return mod.my_macro()

Render Jinja2 macro, ,

0

All Articles