2015-10-18 53 views
0

我正在用Python 2.7構建Django 1.8中的第一個應用程序,我需要將一些值從view.py傳遞給我的HTML模板。在django中創建我的第一個自定義模板

我使用下面的代碼

在Views.py

import datetime 
from django import template 
from django.shortcuts import render_to_response 
from django.template import RequestContext 

register = template.Library() 

class CurrentTimeNode(template.Node): 
    def __init__(self, format_string): 
     self.format_string = str(format_string) 

    def render(self, context): 
     now = datetime.datetime.now() 
     print "Render in CurrentTimeNode:", now 
     return now.strftime(self.format_string) 

@register.simple_tag 
def current_time(format_string): 
    print "Current Time" 
    return CurrentTimeNode(datetime.datetime.now().strftime(format_string)) 

current_time = register.tag(current_time) 


def post(request): 
    datos = "hola" 
    print datos 

    return render_to_response('sitio/post.html', { 'datos':datos} , RequestContext(request)) 

在Post.html

<html> 
    <head> 
     some title 
    </head> 
    <body> 
      {% current_time %} 
      {{ timezone }} 
    </body> 
</html> 

,我想使用標籤 「CURRENT_TIME」 來獲得時間和轉儲在我的html文件中。我收到以下消息的錯誤:

異常類型:TemplateSyntaxError 異常值:
無效的塊標籤: 'CURRENT_TIME'

I the block tag is not recognized

現在缺少的註冊塊標記?

回答

1

如果您可以正確格式化您的代碼(由於某種原因,我無法編輯您的文章),那將會很好。然而,從你的帖子來看,問題在於你沒有加載標籤。您應該將current_time函數放在名爲「templatetags」的文件夾中(該文件夾應與view.py和models.py文件位於同一級別)。添加

__init__.py 

文件確保該目錄被視爲Python包。

接下來,在templatetags文件夾中,將current_time函數放在名爲current_time.py的文件中。在文檔這裏

{% load current_time %} 

尋找更多的信息:那麼在您的模板,這條線添加到模板的頂部https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/

+0

感謝您的反饋,是完美的,我有很多東西需要學習。如何格式化以及使用這種環境的很多小技巧。到目前爲止進展順利 –

+0

@JorgeZavala偉大的,善良的學習。如果我的回覆正確地解決了您的問題,您可以將此問題標記爲已回答 – user2719875

相關問題