Python:如何根据变量更改Django中的页面标题?
我正在使用一个 Django 应用程序,它对不同的“页面”使用相同的模板——基本上,该页面可以是“创建条目”页面或“编辑条目”页面。页面根据以下参数进行更改:
{% if props.data.id %}
Edit
{% else %}
Create
{% endif %}
逻辑是:如果该条目存在 id,则该页面将显示为编辑页面。否则,该页面将显示为“创建”页面。
我希望页面的标题根据相同的参数进行更改。所以页面的两个版本应该是:
Create Entry
Edit Entry
这是我当前正在尝试的代码:
{% if props.data.id %}
{% with action='Edit' %}
{% endwith %}
{% else %}
{% with action='Create' %}
{% endwith %}
{% endif %}
{% block title %} {{ action }} Entry {% endblock %}
我还没有让它工作。我走在正确的轨道上吗?我使用“with”,因为这似乎是在 Django 中设置变量的推荐方法,但我想知道是否有更好的方法来做到这一点。
I am working with a Django app which uses the same template for different 'pages'--basically, the page can either be a "Create Entry" page or an "Edit Entry" page. The page changes based on the following parameters:
{% if props.data.id %}
Edit
{% else %}
Create
{% endif %}
The logic being: if an id exists for this entry, the page will display as a Edit page. Otherwise, the page will display as a Create page.
I would like the title of the page to change depending on the same parameters. So the two versions of the page should be:
Create Entry
Edit Entry
Here's the code I'm currently trying:
{% if props.data.id %}
{% with action='Edit' %}
{% endwith %}
{% else %}
{% with action='Create' %}
{% endwith %}
{% endif %}
{% block title %} {{ action }} Entry {% endblock %}
I haven't gotten this to work yet. Am I on the right track? I was using 'with' since that seems to be the recommended way to set variables in Django, but I'm wondering if there's a better way to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
作为 提及:
您实际上不需要为此设置变量,您可以直接做:
不是一个简单的标题交换所需的,但是您也可以通过变量作为模板上下文的一部分传递到一个变量:
这 在整个模板中,能够将其用作
{{action}}
。有关更复杂的逻辑或行为,您可以在此问题上查看建议 - django {%}在{%} {%} {%} {%else%}标签中的标签?
As the documentation for
with
mentions:You don't really need to set a variable for this, you can directly do:
This is not really required for a simple title swap, but you could also pass in a variable as part of the template context like:
and then you'll be able to use it as
{{ action }}
in the entire template.For more complicated logic or behavior, you can check out the suggestions at this question - Django {% with %} tags within {% if %} {% else %} tags?