在Django的上下文中設(shè)置變量的方法
前一節(jié)的例子只是簡(jiǎn)單的返回一個(gè)值。 很多時(shí)候設(shè)置一個(gè)模板變量而非返回值也很有用。 那樣,模板作者就只能使用你的模板標(biāo)簽所設(shè)置的變量。
要在上下文中設(shè)置變量,在 render() 函數(shù)的context對(duì)象上使用字典賦值。 這里是一個(gè)修改過(guò)的 CurrentTimeNode ,其中設(shè)定了一個(gè)模板變量 current_time ,并沒(méi)有返回它:
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和注冊(cè)給current_time2模板標(biāo)簽的工作留作讀者練習(xí)。)
注意 render() 返回了一個(gè)空字符串。 render() 應(yīng)當(dāng)總是返回一個(gè)字符串,所以如果模板標(biāo)簽只是要設(shè)置變量, render() 就應(yīng)該返回一個(gè)空字符串。
你應(yīng)該這樣使用這個(gè)新版本的標(biāo)簽:
{% current_time2 "%Y-%M-%d %I:%M %p" %} <p>The time is {{ current_time }}.</p>
但是 CurrentTimeNode2 有一個(gè)問(wèn)題: 變量名 current_time 是硬編碼的。 這意味著你必須確定你的模板在其它任何地方都不使用 {{ current_time }} ,因?yàn)?{% current_time2 %} 會(huì)盲目的覆蓋該變量的值。
一種更簡(jiǎn)潔的方案是由模板標(biāo)簽來(lái)指定需要設(shè)定的變量的名稱,就像這樣:
{% get_current_time "%Y-%M-%d %I:%M %p" as my_current_time %} <p>The current time is {{ my_current_time }}.</p>
為此,你需要重構(gòu)編譯函數(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 。
相關(guān)文章
Python中unittest的數(shù)據(jù)驅(qū)動(dòng)詳解
這篇文章主要介紹了Python中unittest的數(shù)據(jù)驅(qū)動(dòng)詳解,數(shù)據(jù)驅(qū)動(dòng)測(cè)試,是一種單元測(cè)試框架,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08使用 Python 寫一個(gè)簡(jiǎn)易的抽獎(jiǎng)程序
這篇文章主要介紹了使用 Python 寫一個(gè)簡(jiǎn)易的抽獎(jiǎng)程序,本文通過(guò)實(shí)例代碼,思路講解的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-12-12django連接oracle時(shí)setting 配置方法
今天小編就為大家分享一篇django連接oracle時(shí)setting 配置方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-08-08python tkinter的消息框模塊(messagebox,simpledialog)
這篇文章主要介紹了python tkinter的消息框模塊,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-11-11解決python便攜版無(wú)法直接運(yùn)行py文件的問(wèn)題
這篇文章主要介紹了解決python便攜版無(wú)法直接運(yùn)行py文件的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09