Skip to content

Instantly share code, notes, and snippets.

@georgemarshall
Created August 9, 2012 03:06
Show Gist options
  • Save georgemarshall/3300549 to your computer and use it in GitHub Desktop.
Save georgemarshall/3300549 to your computer and use it in GitHub Desktop.
{% load handlebars i18n %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
</head>
<body>
{% filter handlebars %}
<script type="text/x-handlebars">
{$ #view App.MenuView $}
<li class="sprite instructions" {$ action "instructions" $}><span class="ir">{% trans 'How to Play' %}</span></li>
<li class="sprite rules" {$ action "rules" $}><span class="ir">{% trans 'Rules' %}</span></li>
<li class="sprite leaderboard" {$ action "leaderboard" $}><span class="ir">{% trans 'Leaderboard' %}</span></li>
<li class="sprite suggest" {$ action "suggest" $}><span class="ir">{% trans 'Suggest Friends' %}</span></li>
{$ /view $}
</script>
{% endfilter %}
</body>
</html>
"""Helper functions for using Handlbar template withing Django templates"""
import re
from django.template.base import Library
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
HANDLEBARS_TAG_START = '{$'
HANDLEBARS_TAG_END = '$}'
_handlebars_escapes = (
(re.compile(r'%s[\s]*' % re.escape(HANDLEBARS_TAG_START)), '{{'),
(re.compile(r'[\s]*%s' % re.escape(HANDLEBARS_TAG_END)), '}}')
)
register = Library()
def escape_handlebars(value):
"""Replaces substitute tags with handlebar tags"""
for o, n in _handlebars_escapes:
value = mark_safe(re.sub(o, n, force_unicode(value)))
return value
@register.filter('handlebars')
def handlebars_filter(value):
"""Replaces substitute tags with handlebar tags"""
return escape_handlebars(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment