Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zaki-yama/cb27ee31e664f5a23a03 to your computer and use it in GitHub Desktop.
Save zaki-yama/cb27ee31e664f5a23a03 to your computer and use it in GitHub Desktop.
[django] カスタムテンプレートタグ
# -*- coding: utf-8 -*-
import datetime
from django import template
register = template.Library()
# これかデコレータ(@register.tag)によってタグを登録する
# register.tag('current_time', do_current_time)
# name を省略すると関数名をそのままタグ名として使用する
@register.tag(name='current_time')
def do_current_time(parser, token):
try:
# split_contents() knows not to split quoted strings.
tag_name, format_string = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("%r tag requires a single argument" % token.contents.split()[0])
if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")):
raise template.TemplateSyntaxError("%r tag's argument should be in quotes" % tag_name)
return CurrentTimeNode(format_string[1:-1])
class CurrentTimeNode(template.Node):
def __init__(self, format_string):
self.format_string = format_string
def render(self, context):
return datetime.datetime.now().strftime(self.format_string)
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
urlpatterns = patterns('',
(r'^', TemplateView.as_view(template_name='custom_template_tags/main_page.html')),
)
{% load current_time %}
<html>
<head>
</head>
<body>
<p>The time is {% current_time '%Y-%m-%d %I:%M %p' %}.</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment