在 jinja2 模板中创建 Flask 应用程序 url 的链接') def get_post(年、月、标题): # 我的代码 要显示 l...</desc> <question vote="45"> <p>在我的 Flask 应用程序中,我有一个显示帖子的视图</p> <pre><code>@post_blueprint.route('/post/<int:year>/<int:month>/<title>') def get_post(year,month,title): # My code </code></pre> <p>要显示最后 10 条条目,我有以下视图:</p> <pre><code>@post_blueprint.route('/posts/') def get_all_posts(): # My code return render_template('p.html',posts=posts) </code></pre> <p>现在,当我显示最后 10 篇帖子时,我想将帖子的标题转换为超链接。 目前我必须在我的 jinja 模板中执行以下操作才能实现此目的:</p> <pre><code><a href="/post/{{year}}/{{month}}/{{title}}">{{title}}</a> </code></pre> <p>有什么方法可以避免对 url 进行硬编码吗? </p> <p>像 <pre><code>url_for</code></pre> 函数一样,用于创建 Flask url,如下所示:</p> <pre><code>url_for('view_name',**arguments) </code></pre> <p>我尝试过寻找一个,但找不到。</p> </question> <answer tick="true" vote="88"> <p>我觉得你在这里问了两个问题,但我会尝试......</p> <p>对于发布网址,您可以这样做:</p> <pre><code><a href="{{ url_for('post_blueprint.get_post', year=year, month=month, title=title)}}"> {{ title }} </a> </code></pre> <p>要处理静态文件,我强烈建议使用像 <a href="http://flask-assets.readthedocs.org/en/latest/index.html" rel="nofollow noreferrer">Flask-Assets</a> 这样的资产管理器,但要使用普通烧瓶来做到这一点:</p> <pre><code>{{ url_for('static', filename='[filenameofstaticfile]') }} </code></pre> <p>如果您想了解更多信息,我强烈建议您阅读。 <a href="http://flask.pocoo.org/docs/quickstart/#static-files" rel="nofollow noreferrer">http://flask.pocoo.org/docs/quickstart/#static-files</a> 和 <a href="http://flask.pocoo.org/docs/quickstart/#url-building" rel="nofollow noreferrer">http://flask.pocoo.org/docs/quickstart/#url-building</a></p> <p><strong>编辑使用 kwargs:</strong></p> <p><em>只是以为我会更彻底......</em></p> <p>如果您想像这样使用<pre><code>url_for</code></pre>:</p> <pre><code>{{ url_for('post_blueprint.get_post', **post) }} </code></pre> <p>你必须改变你的观点,像这样:</p> <pre><code>@post_blueprint.route('/posts/') def get_all_posts(): models = database_call_to_fetch_posts() # This is assuming you use some kind of data-model posts = [] for model in models: posts.append(dict(year=model.year, month=model.month, title=model.title)) return render_template('p.html', posts=posts) def database_call_to_fetch_posts(): posts = [] # fetch posts here as a list of objects ... return posts </code></pre> <p>那么你的模板代码可以如下所示:</p> <pre><code>{% for post in posts %} <a href="{{ url_for('post_blueprint.get_post', **post) }}"> {{ post['title'] }} </a> {% endfor %} </code></pre> <p>此时,我实际上会在模型上创建一个方法,这样您就不必将其转换为字典,但走到这一步取决于您:-)。</p> </answer> </body></html>

问题描述 投票:0回答:0
python flask jinja2
© www.soinside.com 2019 - 2024. All rights reserved.