用jinja2寫模板的時候遇到了一些問題,記錄一下
抽出base.html作為模板
之前的小項目寫得都很不規范,模板都是能用就行,基本上只用到if
語句,for
語句和變量。導航欄都是復制粘貼,沒有把共同的部分抽出來。寫模板的時候還應該注意一下不要直接在原來的html上改,這樣容易把html改亂,應該新建一個template
目錄,再一個個寫模板,這樣更好。
參照jinja2的文檔抽出公共部分,如
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
{% block head %}
<link rel="stylesheet" href="style.css" />
<title>{% block title %}{% endblock %} - My Webpage</title>
{% endblock %}
</head>
<body>
<div id="content">{% block content %}{% endblock %}</div>
<div id="footer">
{% block footer %}
© Copyright 2008 by <a href="http://domain.invalid/">you</a>.
{% endblock %}
</div>
</body>
在子模板中填充對應的block
就行,如
{% block title %}
我是標題
{% endblock %}
對於在base.html里有但是子模板里木有的block
,對應位置會采用base.html里的內容。
導航欄怎么設置為active?
很多用到導航欄的情況都會有當前所在位置高亮的設置,假設CSS中.active
設為高亮了,那么在jinja2中就能給base.html傳值,如:
<ul class="bd clearfix">
<li class="team clearfix {% if active == "team" %}now{% endif %}">
<a href="/team">
<div class="circle circle1" title="團隊介紹"></div>
<div class="hover-wrap"></div>
<div class="title">
<p class="en">Team Introduction</p>
<p class="ch">團隊介紹</p>
</div>
</a>
</li>
<li class="group clearfix {% if active == "group" %}now{% endif %}">
<a href="/group">
<div class="circle circle2" title="各組介紹"></div>
<div class="hover-wrap"></div>
<div class="title">
<p class="en">Group Introduction</p>
<p class="ch">各組介紹</p>
</div>
</a>
</li>
<li class="pro clearfix {% if active == "works" %}now{% endif %}">
<a href="/works">
<div class="circle circle3" title="陳列室"></div>
<div class="hover-wrap"></div>
<div class="title">
<p class="en">Portfolio</p>
<p class="ch">陳列室</p>
</div>
</a>
</li>
<li class="part clearfix {% if active == "partner" %}now{% endif %}">
<a href="/partner">
<div class="circle circle4" title="成員風采"></div>
<div class="hover-wrap"></div>
<div class="title">
<p class="en">Our Partner</p>
<p class="ch">成員風采</p>
</div>
</a>
</li>
<li class="re clearfix">
<a href="http://hr.bingyan.net/" target="_blank">
<div class="circle circle5" title="歷屆招新"></div>
<div class="hover-wrap"></div>
<div class="title">
<p class="en">Recruit</p>
<p class="ch">歷屆招新</p>
</div>
</a>
</li>
</ul>
在子模板中,向base.html傳active
的值就行了,我們不只可以通過py文件向jinja2傳值,還能在不同模板之間傳值
{% extends "base.html" %}
{% set active = "group" %}
這樣導航欄就能根據相應的內容顯示高亮的li
了!更多內容參考官方文檔
如何獲取列表的長度?
jinja2支持很多Python的語法,於是我嘗試調用len(lst)
函數,會報錯。
要獲取列表的長度,應該寫成lst|length
或是它的別稱lst|count
參考這個問題