在Django的上下文中設定變數的方法

來源:互聯網
上載者:User
前一節的例子只是簡單的返回一個值。 很多時候設定一個模板變數而非傳回值也很有用。 那樣,模板作者就只能使用你的模板標籤所設定的變數。

要在上下文中設定變數,在 render() 函數的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 ''

(我們把建立函數do_current_time2和註冊給current_time2模板標籤的工作留作讀者練習。)

注意 render() 返回了一個Null 字元串。 render() 應當總是返回一個字串,所以如果模板標籤只是要設定變數, render() 就應該返回一個Null 字元串。

你應該這樣使用這個新版本的標籤:

{% current_time2 "%Y-%M-%d %I:%M %p" %}

The time is {{ current_time }}.

但是 CurrentTimeNode2 有一個問題: 變數名 current_time 是硬式編碼。 這意味著你必須確定你的模板在其它任何地方都不使用 {{ current_time }} ,因為 {% current_time2 %} 會盲目的覆蓋該變數的值。

一種更簡潔的方案是由模板標籤來指定需要設定的變數的名稱,就像這樣:

{% get_current_time "%Y-%M-%d %I:%M %p" as my_current_time %}

The current time is {{ my_current_time }}.

為此,你需要重構編譯函數和 Node 類,如下所示:

import reclass 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)

現在 do_current_time() 把格式字串和變數名傳遞給 CurrentTimeNode3 。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.