Django妯″潡涔媕inja2妯$増

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django妯″潡涔媕inja2妯$増相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/imp' title='imp'>imp   娉ㄩ噴   option   setting   back   鐜   color   pytho   png   

Jinja2锛氭槸 Python 涓嬩竴涓骞挎硾搴旂敤鐨勬ā鏉垮紩鎿庯紝鏄敱Python瀹炵幇鐨勬ā鏉胯瑷€锛屼粬鐨勮璁℃€濇兂鏉ユ簮浜?Django 鐨勬ā鏉垮紩鎿庯紝骞舵墿灞曚簡鍏惰娉曞拰涓€绯诲垪寮哄ぇ鐨勫姛鑳斤紝灏ゅ叾鏄疐lask妗嗘灦鍐呯疆鐨勬ā鏉胯瑷€銆?/span>

鐢变簬django榛樿妯℃澘寮曟搸鍔熻兘涓嶉綈鍏?閫熷害鎱紝鎵€浠ユ垜浠篃鍙互鍦―jango涓娇鐢╦inja2, jinja2瀹gО姣攄jango榛樿妯℃澘寮曟搸蹇?0-20鍊嶃€?/span>

Django涓绘祦鐨勭涓夋柟APP鍩烘湰涓婁篃閮藉悓鏃舵敮鎸丏jango榛樿妯℃澘鍙妀inja2锛屾墍浠ヨ鐢╦inja2涔熶笉浼氭湁澶氬皯闅滅銆?/span>

浣跨敤jinja2妯$増娴佺▼锛?/h1>

1. 瀹夎绗笁鏂规ā鍧楋細

pip intall jinja2 -i 闀滃儚婧?/pre>

澶у鍦ㄥ畨瑁呮椂锛屾渶濂芥寚瀹氫竴涓嬮暅鍍忔簮锛屽惁鍒欏浗鍐呭澶珮鐖繃鏉ュ澶氬皯鏀堕兘浼氭湁鐐规參鐨勩€?/p>

2. 閰嶇疆jinja2锛?/h2>

銆€銆€2.1 鍦―jango椤圭洰涓垱寤簀inja2鏂囦欢锛屽苟鍒涘缓鐜瀵硅薄锛?/h3>
from jinja2 import Environment

def environment(**options):
    env = Environment(**options)

    return env

銆€銆€2.2 鍦―jango椤圭洰鐨勯厤缃枃浠朵腑閰嶇疆jinja2妯$増淇℃伅锛?/h3>

娉ㄦ剰锛?/p>

銆€銆€閰嶇疆鏂囦欢鍗矰jango椤圭洰淇℃伅鐨勯厤缃枃浠讹紝涓€鑸懡鍚嶄负setting.py銆乨ev.py銆乸rop.py銆?/p>

銆€銆€鍦ㄩ厤缃枃浠朵腑閰嶇疆jinja2妯$増鏃讹紝闇€瑕佸厛灏咲jango閰嶇疆鏂囦欢涓嚜甯︾殑妯$増閰嶇疆淇℃伅娉ㄩ噴鎴栧垹闄ゃ€?/p>

TEMPLATES = [
    {
        鈥?/span>BACKEND鈥?/span>: 鈥?/span>django.template.backends.jinja2.Jinja2鈥?/span>,#淇敼1
        鈥?/span>DIRS鈥?/span>: [os.path.join(BASE_DIR, 鈥?/span>templates鈥?/span>)],
        鈥?/span>APP_DIRS鈥?/span>:True,
        鈥?/span>OPTIONS鈥?/span>:{
            鈥?/span>environment鈥?/span>: 鈥?/span>jinja2_env.environment鈥?/span>,# 淇敼2
            鈥?/span>context_processors鈥?/span>:[
                鈥?/span>django.template.context_processors.debug鈥?/span>,
                鈥?/span>django.template.context_processors.request鈥?/span>,
                鈥?/span>django.contrib.auth.context_processors.auth鈥?/span>,
                鈥?/span>django.contrib.messages.context_processors.messages鈥?/span>,
            ],
        },
    },
]

3. 浣跨敤jinja2娓叉煋html妯$増锛?/h2>

銆€銆€3.1 缂栧啓瑙嗗浘锛岃繑鍥瀓inja2妯℃澘锛屽苟浼犻€掓暟鎹繘琛屾覆鏌撱€?/h3>
class IndexView(View):
    
    def get(self, request):
        context = {
            鈥?/span>key鈥?/span>:鈥?/span>value鈥?/span>,
            鈥?/span>msg鈥?/span>:鈥?/span>Hello Jinja2鈥?/span>
        }
        return render(request, 鈥?/span>index.html鈥?/span>, context)

銆€銆€3.2 鍦℉TML妯$増涓帴鏀跺悗绔紶閫掔殑jinja2璇硶鐨勬暟鎹?/h3>
{% if key%}
    <span class="error_tip">{{ key}}</span>
{% endif %}

{% if msg%}
    <span class="error_tip">{{ msg}}</span>
{% endif %}

4. jinja2鐨勮繃婊ゅ櫒锛?/h2>

鎶€鏈浘鐗? src=

5. 鑷畾涔塲inja2杩囨护鍣?/h2>

鍦╦inja2鐜鏂囦欢涓紝杩涜鑷畾涔塲inja2杩囨护鍣細

from jinja2 import Environment

def environment(**options):
    env = Environment(**options)

    # 2.灏嗚嚜瀹氫箟鐨勮繃婊ゅ櫒娣诲姞鍒?鐜涓?/span>
    env.filters[鈥?/span>do_listreverse鈥?/span>] = do_listreverse

    return env

# 1.鑷畾涔夎繃婊ゅ櫒
def do_listreverse(li):
    if li == "B":
        return "鍝堝搱"

以上是关于Django妯″潡涔媕inja2妯$増的主要内容,如果未能解决你的问题,请参考以下文章

re 妯″潡銆乼yping 妯″潡銆乧ollections 妯″潡

python妯″潡涓€涔媐aker妯″潡

璁捐妯″紡锛歴tate妯″紡

璁捐妯″紡

os妯″潡

璁捐妯″紡-浠g悊妯″紡