Skip to content

Instantly share code, notes, and snippets.

@jgorset
Created August 17, 2012 12:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgorset/3378321 to your computer and use it in GitHub Desktop.
Save jgorset/3378321 to your computer and use it in GitHub Desktop.
Side-by-side comparison of template tags in Django and Ruby on Rails

Side-by-side comparison of template tags in Django and Ruby on Rails

Format the current time

Django

from django import template
import datetime

register = template.Library()

@register.tag
def do_current_time(parser, token):

    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)

    try:
        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])

Ruby on Rails

def current_time format
    Time.now.strftime format

Inject a variable into the template's context

Django

from django import template

from news.models import Article

register = template.Library()

@register.tag
def get_categories(parser_token):

    class Node(template.Node):

        def __init__(self, variable_name):
            self.variable_name = variable_name
    
        def render(self, context):
            context[self.variable_name] = Category.objects.all()
            return ''

    bits = token.contents.split()

    if len(bits) != 3:
        raise template.TemplateSyntaxError, "get_categories takes exactly three arguments"
    if bits[1] != 'as':
        raise template.TemplateSyntaxError, "get_categories' second argument must be 'as'"

    return Node(bits[2])

Ruby on Rails

def categories
    Category.all
@mbaechtold
Copy link

You could pass the current time to the context and then use the built-in filter https://docs.djangoproject.com/en/dev/ref/templates/builtins/#time, i.e. {{ value|time:"H:i" }}

@mbaechtold
Copy link

Or the built-in template tag "now": https://docs.djangoproject.com/en/dev/ref/templates/builtins/#now, i.e. It is {% now "jS F Y H:i" %}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment