Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
547 views
in Technique[技术] by (71.8m points)

flask - 替换字符串中的Jinja2块(Replace Jinja2 block inside string)

I want to replace a part of a url_for link with a template block that specifies the filename.

(我想用指定文件名的url_for替换url_for链接的一部分。)

I followed something similar to Block tag inside url_for() in Jinja2 .

(我在Jinja2中遵循类似于url_for()中的Block标签的内容 。)

But I want to put the image in the base templates main block.

(但是我想将图像放在基本模板main块中。)

This is the base file:

(这是base文件:)

{% macro error_img(name) -%}
<img class="center-block" viewBox="0 0 60 55" width="300" height="300"
     src="{{ url_for('static', filename=name) }}" alt=""/>
{%- endmacro %}

{% block main %}
<div class="container">
  <div class="row text-center">
    <div class="col"> <!-- I want the image HERE -->
      {{ error_img(name) }}
    </div>1
  </div>
</div>

And in the child template:

(在子模板中:)

{% extends "errors/base.html" %}

{{ error_img("media/errors/404.svg") }}

But I get an image with the url: http://localhost:5000/static/

(但是我得到的图像带有URL: http://localhost:5000/static/)

  ask by Mustaqim Malim translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For some reason a block is required around the macro :

(由于某种原因,在macro周围需要一个block :)

base.html

{% macro error_img(name) -%}
<img class="center-block" viewBox="0 0 60 55" width="300" height="300"
     src="{{ url_for('static', filename=name) }}" alt=""/>
{%- endmacro %}

{% block main %}
<div class="container">
  <div class="row text-center">
    <div class="col"> <!-- I want the image HERE -->
      {% block img %}
        {{ error_img(name) }}
      {% endblock%}
    </div>
  </div>

child.html

{% extends "errors/base.html" %}

{% block img %}
{{ error_img('media/errors/404.svg') }}
{% endblock %}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...