Commit 59ece1fe by Chris Wanstrath

basic subclassable view support

parent e822dab9
Hi {{thing}}!
\ No newline at end of file
import pystache
class Simple(pystache.View):
template_path = 'examples'
def thing(self):
return "world"
from pystache.template import Template
from pystache.view import View
def render(template, context={}, **kwargs):
context = context.copy()
......
import pystache
import os.path
class View(object):
# Path where this view's template(s) live
template_path = '.'
# Extension for templates
template_extension = 'mustache'
# Absolute path to the template itself. Pystache will try to guess
# if it's not provided.
template_file = None
# Contents of the template.
template = None
def __init__(self, template=None, context={}, **kwargs):
self.template = template
self.context = context
for key in kwargs:
self.context[key] = kwargs[key]
def load_template(self):
if self.template:
return self.template
if not self.template_file:
name = self.template_name() + '.' + self.template_extension
self.template_file = os.path.join(self.template_path, name)
return open(self.template_file, 'r').read()
def template_name(self):
return self.__class__.__name__
def render(self):
template = self.load_template()
return pystache.render(template, self.context)
import unittest
import pystache
from examples.simple import Simple
class TestView(unittest.TestCase):
def test_basic(self):
view = Simple("Hi {{thing}}!", { 'thing': 'world' })
self.assertEquals(view.render(), "Hi world!")
def test_kwargs(self):
view = Simple("Hi {{thing}}!", thing='world')
self.assertEquals(view.render(), "Hi world!")
def test_template_load(self):
view = Simple(thing='world')
self.assertEquals(view.render(), "Hi world!")
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment