Call flag functions inside templates

I am working on my site with Flask and Jinja templates and I have a weird error about images in templates. I have a template post.html

that inherits from base.html

and is passed a post object from a SQL database to it. The problem is that some of the Jinja template functions are not called when I do this, namely the HTML image tags are not loading correctly based on the call url_for()

. Regular HTML tags are nice as I use |safe

them to get processed.

Example from template post.html

:

{% extends "base.html" %}
{% block content %}
<div class="post-description">
        <p>
            {{post.body|safe}}       
        </p>
</div>
{% endblock %}

      

An example from this call post.body

:

<b> I work, and am bolded</b>
<img src="{{ url_for('static', filename = 'images/randomImg.png') }}">

      

As long as the bold text renders well, url_for

never gets called. In the original source (on the website itself) it is easy to check as the src link is never rendered properly, unlike other pages where the function is evaluated. If I copy / paste the line <img>

so mine now post.html

looks like this:

{% extends "base.html" %}
{% block content %}
<div class="post-description">
        <p>
            <img src="{{ url_for('static', filename = 'images/randomImg.png') }}">
            {{post.body|safe}}       
        </p>
</div>
{% endblock %}

      

The first call to the image loads fine, but the one inside the post.body doesn't. I'm not sure if there is a Flask or Jinja way to get him to evaluate it, but I hope.

Edit solution: The trick was to make the post.body inside the call first render_template_string

, since this correctly "filled" the calls url_for

so that it render_template

could then evaluate correctly.

+3


source to share


1 answer


post.body

wasn't handled the way you want it because jinja2 doesn't try to restore its own default output, which makes sense.

You can display the body of the message and then render the response:



@app.route("/some/path")
def some_view():
    # ...
    post = Post.query.first()
    rendered_post_body = render_template_string(post.body)
    return render_template("some_template.html", post_body=rendered_post_body)

      

+2


source







All Articles