Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Three revisions #17

Merged
4 commits merged into from

1 participant

@rockyburt
Collaborator

1) pep8 cleanups
2) early IJinja2Environment registration
3) new add_jinja2_assetdirs api function

You can ignore the previous pull request... still getting used to this.

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Feb 3, 2011
  1. @rockyburt

    Pep8 cleanups

    rockyburt authored
Commits on Feb 12, 2011
  1. @rockyburt
  2. @rockyburt
Commits on Feb 13, 2011
  1. @rockyburt
This page is out of date. Refresh to see the latest.
View
3  docs/conf.py
@@ -17,7 +17,8 @@
# make it absolute, like shown here.
#sys.path.append(os.path.abspath('some/directory'))
-import sys, os
+import sys
+import os
parent = os.path.dirname(os.path.dirname(__file__))
sys.path.append(os.path.abspath(parent))
View
95 pyramid_jinja2/__init__.py
@@ -10,6 +10,7 @@
from pyramid.exceptions import ConfigurationError
from pyramid.resource import abspath_from_resource_spec
+
class IJinja2Environment(Interface):
pass
@@ -26,14 +27,17 @@ def asbool(obj):
"String is not true/false: %r" % obj)
return bool(obj)
+
def maybe_import_string(val):
if isinstance(val, basestring):
return import_string(val.strip())
return val
+
def splitlines(s):
return filter(None, [x.strip() for x in s.splitlines()])
+
def parse_filters(filters):
# input must be a string or dict
result = {}
@@ -46,54 +50,72 @@ def parse_filters(filters):
result[name] = maybe_import_string(impl)
return result
+
def parse_extensions(extensions):
if isinstance(extensions, basestring):
extensions = splitlines(extensions)
- return [ maybe_import_string(x) for x in extensions ]
+ return [maybe_import_string(x) for x in extensions]
-def renderer_factory(info):
- registry = info.registry
- settings = info.settings
+
+def directory_loader_factory(settings):
+ input_encoding = settings.get('jinja2.input_encoding', 'utf-8')
+ directories = settings.get('jinja2.directories')
+ if directories is None or directories.strip() == '':
+ raise ConfigurationError('Jinja2 template used without a '
+ '``jinja2.directories`` setting')
+ if isinstance(directories, basestring):
+ directories = splitlines(directories)
+ directories = [abspath_from_resource_spec(d) for d in directories]
+ loader = FileSystemLoader(directories, encoding=input_encoding)
+ return loader
+
+
+def get_or_build_default_environment(settings, registry):
environment = registry.queryUtility(IJinja2Environment)
- if environment is None:
- reload_templates = settings.get('reload_templates', False)
- directories = settings.get('jinja2.directories')
- input_encoding = settings.get('jinja2.input_encoding', 'utf-8')
- autoescape = settings.get('jinja2.autoescape', True)
- extensions = settings.get('jinja2.extensions', '')
- filters = settings.get('jinja2.filters', '')
- if directories is None:
- raise ConfigurationError(
- 'Jinja2 template used without a ``jinja2.directories`` setting')
- if isinstance(directories, basestring):
- directories = splitlines(directories)
- directories = [ abspath_from_resource_spec(d) for d in directories ]
- loader = FileSystemLoader(directories, encoding=input_encoding)
- autoescape = asbool(autoescape)
- extensions = parse_extensions(extensions)
- filters = parse_filters(filters)
- environment = Environment(loader=loader,
- auto_reload=reload_templates,
- autoescape=autoescape,
- extensions=extensions)
- environment.filters.update(filters)
- registry.registerUtility(environment, IJinja2Environment)
+ if environment is not None:
+ return environment
+
+ _setup_environments(settings, registry)
+ return registry.queryUtility(IJinja2Environment)
+
+
+def _setup_environments(settings, registry):
+ reload_templates = settings.get('reload_templates', False)
+ autoescape = settings.get('jinja2.autoescape', True)
+ extensions = settings.get('jinja2.extensions', '')
+ filters = settings.get('jinja2.filters', '')
+ autoescape = asbool(autoescape)
+ extensions = parse_extensions(extensions)
+ filters = parse_filters(filters)
+ environment = Environment(loader=directory_loader_factory(settings),
+ auto_reload=reload_templates,
+ autoescape=autoescape,
+ extensions=extensions)
+ environment.filters.update(filters)
+ registry.registerUtility(environment, IJinja2Environment)
+
+
+def renderer_factory(info):
+ environment = get_or_build_default_environment(
+ info.settings, info.registry)
return Jinja2TemplateRenderer(info, environment)
+
class Jinja2TemplateRenderer(object):
implements(ITemplateRenderer)
template = None
+
def __init__(self, info, environment):
self.info = info
self.environment = environment
-
+
def implementation(self):
return self.template
@property
def template(self):
return self.environment.get_template(self.info.name)
-
+
def __call__(self, value, system):
try:
system.update(value)
@@ -103,6 +125,19 @@ def __call__(self, value, system):
return result
+def add_jinja2_assetdirs(config_or_registry, assetdirs):
+ registry = config_or_registry
+ if hasattr(registry, 'registry'):
+ registry = registry.registry
+ env = get_or_build_default_environment(
+ registry.settings, registry)
+ if isinstance(assetdirs, basestring):
+ assetdirs = [assetdirs]
+ for d in assetdirs:
+ env.loader.searchpath.append(abspath_from_resource_spec(d))
+
+
def includeme(config):
config.add_renderer('.jinja2', renderer_factory)
-
+ get_or_build_default_environment(
+ config.registry.settings, config.registry)
View
3  pyramid_jinja2/filters.py
@@ -6,6 +6,7 @@
'route_url_filter',
]
+
def model_url_filter(model, *elements, **kw):
"""A filter from ``model`` to a string representing the absolute URL.
this filter call `pyramid.url.resource_url`.
@@ -13,10 +14,10 @@ def model_url_filter(model, *elements, **kw):
request = get_current_request()
return resource_url(model, request, *elements, **kw)
+
def route_url_filter(route_name, *elements, **kw):
"""A filter from ``route_name`` to a string representing the absolute URL.
this filter call `pyramid.url.route_url`.
"""
request = get_current_request()
return route_url(route_name, request, *elements, **kw)
-
View
1  pyramid_jinja2/paster.py
@@ -1,6 +1,7 @@
from paste.script.templates import Template
from paste.util.template import paste_script_template_renderer
+
class Jinja2ProjectTemplate(Template):
_template_dir = 'paster_template'
summary = 'pyramid jinja2 starter project'
View
1  pyramid_jinja2/paster_template/+package+/models.py
@@ -3,5 +3,6 @@ class MyModel(object):
root = MyModel()
+
def get_root(environ):
return root
View
20 pyramid_jinja2/tests/test_it.py
@@ -255,10 +255,30 @@ def test_it(self):
from pyramid_jinja2 import includeme
from pyramid_jinja2 import renderer_factory
config = testing.setUp()
+ config.registry.settings['jinja2.directories'] = '/foobar'
includeme(config)
utility = config.registry.getUtility(IRendererFactory, name='.jinja2')
self.assertEqual(utility, renderer_factory)
+
+class Test_add_jinja2_assetdirs(unittest.TestCase):
+ def test_it(self):
+ from pyramid_jinja2 import add_jinja2_assetdirs
+ from pyramid_jinja2 import includeme
+ from pyramid_jinja2 import IJinja2Environment
+ import os
+ config = testing.setUp()
+ config.registry.settings['jinja2.directories'] = 'foobar'
+ includeme(config)
+ utility = config.registry.getUtility(IJinja2Environment)
+ self.assertEqual([x.split(os.sep)[-1]
+ for x in utility.loader.searchpath], ['foobar'])
+ add_jinja2_assetdirs(config, 'grrr')
+ self.assertEqual([x.split(os.sep)[-1]
+ for x in utility.loader.searchpath],
+ ['foobar', 'grrr'])
+
+
class DummyEnvironment(object):
def get_template(self, path):
self.path = path
View
7 setup.py
@@ -23,7 +23,7 @@
setup(name='pyramid_jinja2',
version='0.5',
description='Jinja2 template bindings for the Pyramid web framework',
- long_description=README + '\n\n' + CHANGES,
+ long_description=README + '\n\n' + CHANGES,
classifiers=[
"Intended Audience :: Developers",
"Programming Language :: Python",
@@ -38,12 +38,11 @@
packages=find_packages(),
include_package_data=True,
zip_safe=False,
- tests_require = ['pyramid>=1.0a10', 'pyramid_zcml', 'Jinja2'],
+ tests_require=['pyramid>=1.0a10', 'pyramid_zcml', 'Jinja2'],
install_requires=['pyramid>=1.0a10', 'pyramid_zcml', 'Jinja2'],
test_suite="pyramid_jinja2",
- entry_points = """\
+ entry_points="""
[paste.paster_create_template]
pyramid_jinja2_starter=pyramid_jinja2.paster:Jinja2ProjectTemplate
"""
)
-
Something went wrong with that request. Please try again.