英文:
Jinja modify base.html depending on the page
问题
我在我的Flask项目的模板中使用Jinja。
我的问题是:如何在你位于相应页面时更改侧边栏中的某个元素的颜色(该元素位于base.html文件中)?
我的意思是,假设我有一个侧边栏,其中包含以下标题,这些标题链接到它们对应的页面:dashboard,feature1,feature2。
如果我想要在进入feature1时将feature1的颜色更改,然后再将feature1的颜色更改回原始颜色,并在单击并转到dashboard页面时将dashboard更改为选定的颜色,我该如何操作?
因为我真的不知道如何简单地完成这个操作,而不是在每个页面的HTML模板中创建新内容。
提前感谢!
英文:
I'm using jinja in the templates of my flask project.
My question is : how to change the color of one of the elements of the sidebar (which is in base.html file) when you are on the corresponding page ?
I mean let's say I have a sidebar with the following titles linked to their corresponding page : dashboard, feature1, feature2.
How can I do if I want feature1 to change of color when I am on feature1, then change back feature1 to its original color and turn dashboard to the selected color when I click and go on dashboard page ?
Because I don't really know how to simply do it instead of creating a new content in each of my pages' html template.
Thanks in advance !
答案1
得分: 1
.active {
background-color: 红色;
}
@app.route('/')
def dashboard():
# ...
<a
class="{% if request.endpoint == 'dashboard' %}active{% endif %}"
href="{{ url_for('dashboard') }}"
>仪表盘</a>
英文:
You can use a CSS class for the active link. This defines the style properties for the menu entry of the currently used page.
.active {
background-color: red;
}
To add the class to the menu item, you can use a simple if condition using the request object. Here you can compare whether the current request is the same as the identifier of the endpoint.
@app.route('/')
def dashboard():
# ...
<a
class="{% if request.endpoint == 'dashboard' %}active{% endif %}"
href="{{ url_for('dashboard') }}"
>Dashboard</a>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论