You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Side-by-side comparison of template tags in Django and Ruby on Rails
Format the current time
Django
fromdjangoimporttemplateimportdatetimeregister=template.Library()
@register.tagdefdo_current_time(parser, token):
classCurrentTimeNode(template.Node):
def__init__(self, format_string):
self.format_string=format_stringdefrender(self, context):
returndatetime.datetime.now().strftime(self.format_string)
try:
tag_name, format_string=token.split_contents()
exceptValueError:
raisetemplate.TemplateSyntaxError("%r tag requires a single argument"%token.contents.split()[0])
ifnot (format_string[0] ==format_string[-1] andformat_string[0] in ('"', "'")):
raisetemplate.TemplateSyntaxError("%r tag's argument should be in quotes"%tag_name)
returnCurrentTimeNode(format_string[1:-1])
Ruby on Rails
defcurrent_timeformatTime.now.strftimeformat
Inject a variable into the template's context
Django
fromdjangoimporttemplatefromnews.modelsimportArticleregister=template.Library()
@register.tagdefget_categories(parser_token):
classNode(template.Node):
def__init__(self, variable_name):
self.variable_name=variable_namedefrender(self, context):
context[self.variable_name] =Category.objects.all()
return''bits=token.contents.split()
iflen(bits) !=3:
raisetemplate.TemplateSyntaxError, "get_categories takes exactly three arguments"ifbits[1] !='as':
raisetemplate.TemplateSyntaxError, "get_categories' second argument must be 'as'"returnNode(bits[2])
Why so much Python code to get your categories ?
Tried Django context processors ?