在Django的上下文中設置變量的方法
前一節(jié)的例子只是簡單的返回一個值。 很多時候設置一個模板變量而非返回值也很有用。 那樣,模板作者就只能使用你的模板標簽所設置的變量。
要在上下文中設置變量,在 render() 函數(shù)的context對象上使用字典賦值。 這里是一個修改過的 CurrentTimeNode ,其中設定了一個模板變量 current_time ,并沒有返回它:
class CurrentTimeNode2(template.Node):
def __init__(self, format_string):
self.format_string = str(format_string)
def render(self, context):
now = datetime.datetime.now()
context['current_time'] = now.strftime(self.format_string)
return ''
(我們把創(chuàng)建函數(shù)do_current_time2和注冊給current_time2模板標簽的工作留作讀者練習。)
注意 render() 返回了一個空字符串。 render() 應當總是返回一個字符串,所以如果模板標簽只是要設置變量, render() 就應該返回一個空字符串。
你應該這樣使用這個新版本的標簽:
{% current_time2 "%Y-%M-%d %I:%M %p" %}
<p>The time is {{ current_time }}.</p>
但是 CurrentTimeNode2 有一個問題: 變量名 current_time 是硬編碼的。 這意味著你必須確定你的模板在其它任何地方都不使用 {{ current_time }} ,因為 {% current_time2 %} 會盲目的覆蓋該變量的值。
一種更簡潔的方案是由模板標簽來指定需要設定的變量的名稱,就像這樣:
{% get_current_time "%Y-%M-%d %I:%M %p" as my_current_time %}
<p>The current time is {{ my_current_time }}.</p>
為此,你需要重構編譯函數(shù)和 Node 類,如下所示:
import re
class CurrentTimeNode3(template.Node):
def __init__(self, format_string, var_name):
self.format_string = str(format_string)
self.var_name = var_name
def render(self, context):
now = datetime.datetime.now()
context[self.var_name] = now.strftime(self.format_string)
return ''
def do_current_time(parser, token):
# This version uses a regular expression to parse tag contents.
try:
# Splitting by None == splitting by spaces.
tag_name, arg = token.contents.split(None, 1)
except ValueError:
msg = '%r tag requires arguments' % token.contents[0]
raise template.TemplateSyntaxError(msg)
m = re.search(r'(.*?) as (\w+)', arg)
if m:
fmt, var_name = m.groups()
else:
msg = '%r tag had invalid arguments' % tag_name
raise template.TemplateSyntaxError(msg)
if not (fmt[0] == fmt[-1] and fmt[0] in ('"', "'")):
msg = "%r tag's argument should be in quotes" % tag_name
raise template.TemplateSyntaxError(msg)
return CurrentTimeNode3(fmt[1:-1], var_name)
現(xiàn)在 do_current_time() 把格式字符串和變量名傳遞給 CurrentTimeNode3 。
相關文章
python index() 與 rindex() 方法的使用示例詳解
這篇文章主要介紹了python index() 與 rindex() 方法的使用,需要的朋友可以參考下2022-12-12
Python中from…import *和import區(qū)別小結
本文介紹了Python中import和from...import兩種導入模塊的區(qū)別,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-12-12
在PyCharm中找不到Conda創(chuàng)建的環(huán)境的解決方法
本文主要介紹了在PyCharm中找不到Conda創(chuàng)建的環(huán)境的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-07-07

