These are bindings for the Jinja2 templating system for the Pyramid web framework.
See https://docs.pylonsproject.org/projects/pyramid-jinja2/en/latest/ for documentation or index.rst
in the docs
sub-directory of the source distribution.
Jinja2 templating system bindings for the Pyramid web framework
Home Page: https://docs.pylonsproject.org/projects/pyramid-jinja2/en/latest/
License: Other
These are bindings for the Jinja2 templating system for the Pyramid web framework.
See https://docs.pylonsproject.org/projects/pyramid-jinja2/en/latest/ for documentation or index.rst
in the docs
sub-directory of the source distribution.
Currently, if a bytecode cache is enabled, pyramid_jinja2 registers an atexit callback to clean out the cache. As I understand the bytecode cache, this seems to defeat much of the purpose of having one. Compiled templates (up to a limit set by cache_size
, at least) are already cached in memory. For me, much of the point of enabling a bytecode cache is to minimize app startup time — which it won’t do if it gets deleted upon app termination.
If the bytecode cache is wiped at exit, and there are fewer than cache_size
templates used by the app, the bytecode cache does not really help at all (if I understand things correctly.) In this case, the compiled templates all come straight from the in-memory cache, the filesystem bytecode cache is redundant.
If I had my druthers:
bytecode_caching
setting would default to off.I'd be happy to submit a pull request if there is a consensus on how to proceed.
When you add a directory to the jinja-search path normally, like this:
config.add_jinja2_search_path('pyramid_jinja_issue:templates', name='.html')
then Pyramid/Jinja won't find the template when it's located in a sub-directory. This one works:
@view_config(route_name='works', renderer='some_template.html')
def my_view(request):
...
but this one doesn't work:
@view_config(route_name='broken', renderer='email/other_template.html')
def my_view(request):
...
Providing the full asset-specification works again, but the other way based on the search-path should work, too.
Example to reproduce here (simply try the 3 different routes /works
, /works2
, /broken
:
https://github.com/martinstein/pyramid_jinja_issue
I cannot get I18n working?
I need to add gettext calls to context globals.
There is no any example on the web of doing so.
I have ended up with:
config.include('pyramid_jinja2')
includeme(config)
jinja2_environment = registry.queryUtility(IJinja2Environment)
jinja2_environment.install_gettext_callables(
lambda x: translations.ugettext(x),
lambda s, p, n: translations.ungettext(s, p, n),
newstyle=True
)
but it doesn't work as well.
Please, provide any sample of that.
Hi, I've realized that the i18n.py functions are out of date. The gettext functions in the jinja2 documentation allow variable mapping with different/shorter syntax.
See #33 (comment)
When switching the HTTP_HOST of a website by changing the port or the URL on which the application is being served from the templates seem to be incorrectly being cached and will not update when the application is run again with the new HTTP_HOST. Temporary solution is to enable the following option:
jinja2.bytecode_caching = false
Otherwise I have had no luck. On the Pocoo irc i was linked to this in addition, it may serve to help, but i didn't end up using it. http://stackoverflow.com/questions/8608743/whats-the-best-way-to-disable-jinja2-template-caching-in-bottle-py/8609414#8609414
The docs reference:
from pyramid.jinja2 import render_to_response
return render_to_response('foo.jinja2', {'foo':1})
however, I get an ImportError that pyramid has no module jinja2
Module pyramid_jinja2 has no method render_to_response()
Any thoughts?
Pyramid 1.5.7
pyramid-debugtoolbar
Tried on python 3.4 and 3.5
To use pyramid_jinja2 on python3 one has to disable bytecodecache. See pallets/jinja#240
Following the jinja2 documentation I've find out a way to load different templates from a unique view. But taking into account that Pyramid_jinja2 was already configured in my app with a default path for templates. I was wondering if there is another way more elegant to get this done. This is my approach:
from jinja2 import Environment, PackageLoader
@view_config(context=Test)
def test_view(request):
env = Environment(loader=PackageLoader('project_name', 'templates'))
template = env.get_template('section1/example1.jinja2')
return Response(template.render(data={'a':1,'b':2}))
Can I get an instance of the pyramid_jinja2 environment from somewhere so I don't have to set again the default path for templates in the view?
Another note about me doing Getting Started docs. I'm advocating that complete newbies start with debugtoolbar. If I'm preaching pyramid_jinja2 and its starter template, it would be better if that starter template made pyramid_debugtoolbar a dependency and put it in development.ini pyramid includes.
Similarly, some other nice-to-haves in the scaffold:
root@vre [/home/vrnet/public_html/env]# sudo -u vrnet ./bin/pip install pyramid_jinja2
Downloading/unpacking pyramid-jinja2
Running setup.py egg_info for package pyramid-jinja2
Traceback (most recent call last):
File "<string>", line 16, in <module>
File "/home/vrnet/public_html/env/build/pyramid-jinja2/setup.py", line 21, in <module>
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
File "/home/vrnet/public_html/env/lib64/python3.3/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 131: ordinal not in range(128)
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 16, in <module>
File "/home/vrnet/public_html/env/build/pyramid-jinja2/setup.py", line 21, in <module>
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
File "/home/vrnet/public_html/env/lib64/python3.3/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 131: ordinal not in range(128)
----------------------------------------
Command python setup.py egg_info failed with error code 1 in /home/vrnet/public_html/env/build/pyramid-jinja2
templates/foo.jinja2
{% extends 'middle.jinja2' %}
templates/middle.jinja2
{% extends 'base.jinja2' %}
templates/base.jinja2
Yo
starting point:
body = render('templates/foo.jinja2', {})
Currently is raising an error like
TemplateNotFound: base.jinja2; asset=base.jinja2; searchpath=['/Users/michael/work/oss/pyramid_jinja2/pyramid_jinja2/tests/templates', '/Users/michael/work/oss/pyramid_jinja2/pyramid_jinja2/tests']; parent=middle.jinja2@@FROM_PARENT@@templates/foo.jinja2
The template being loaded here is base.jinja2@@FROM_PARENT@@middle.jinja2@@FROM_PARENT@@templates/foo.jinja2
.
I'm opening this issue temporarily as I try to think through what the appropriate search order should be here. For example, let's assume something like C/base.jinja2@@FROM_PARENT@@B/middle.jinja2@@FROM_PARENT@@A/foo.jinja2
.
In this case we should test ['A/B/C/base.jinja2', 'A/C/base.jinja2', 'C/base.jinja2']
.
Given the following templates directory arrangement:
templates
base.html
admin/
base.html
index.html
Where admin/index.html
has the following extends tag:
{% extends 'admin/base.html' %}
And admin/base.html
has the following extends tag:
{% extends 'base.html' %}
{# The path I am trying to say here is to inherit from the templates/base.html #}
What happens is that the following error is raised:
RuntimeError: maximum recursion depth exceeded while calling a Python object
Now, what I am not sure if whether my configuration is just wrong or something as to why it works that way with v1.9 but not in v2.3.2. I think though is that it shouldn't throw a recursive error because I wanted a search path approach.
Just for additional information, here is the snippet of my pyramid configuration:
# config.ini
jinja2.directories =
alleycat.web:frontend/templates
jinja2.extensions =
jinja2.ext.with_
jinja2.ext.do
jinja2.ext.loopcontrols
And here is the snippet from my python configurator code:
from pyramid.config import Configurator
configurator = Configurator(**{
'renderers': (
('.html', 'pyramid_jinja2.renderer_factory'),
)
})
Currently you have to get the Environment
and do env.tests['foo'] = some_test
and it might be nice to do it from the INI file similar to filters.
Currently with static_url filter, generated URL contains proto://host:port. There should be another filter or way to generate the absolute resource path only.
Like
{{ 'app:static/js/myjs.js'|static_url }}
generates http://localhost:6543/static/js/myjs.js. There should be way to generate only /static/js/myjs.js
When a caller-relative template extends a path-based template and the SmartAssetSpecLoader.get_source()
method tries to load the path-based template it fails because the filename is prefixed with the caller path "caller.path:filename.html"
and the TemplateNotFound
is raised.
This was introduced in this commit:
ed4a5a3#diff-e576f6688e12c63d080f32947bab398d
Hi,
pyramid, pyramid_jinja2, sqla ..
some background: i'm a pyramid newbie so the "solution" i'm applying to my "problem" may not be the "best".
Pyramid's virtual hosting as described here
eg.
http://example.com - main website
http://example.com/admin - admin site as a separate wsgi app
defined a "main" composite app - important parts below:
[DEFAULT]
..
[composite:main]
use = egg:Paste#urlmap
/ = web
/admin = admin
[app:web]
use = egg:Example#main
jinja2.directories = example:templates/web
[app:admin]
use = egg:Example#admin
jinja2.directories = example:templates/admin
...
This also means that i have 2 separate entry points in my setup.py (main and admin) which in turn means that i'm creating 2 Configurator() instances inorder to create the corresponding wsgi apps (both entry points being app factories that have to return wsgi apps - Configurator().make_wsgi_app() ).
The value of jinja2.directories for the 1st app created is clobbered by the jinja2.directories value for the last app created.
Please note that this might be a "faux" problem because am not sure if its "right" to create 2 (or more) configurator instances within the same pyramid project. On the other hand i don't see how we can avoid creating several of those when creating a composite app (or maybe composite app is not the way to go..?).
Hope i've been precise..
Regards,
Eric.
config.get_jinja2_environment() is not available until after config.make_wsgi_app(). This is a change from the past.
To reproduce, simply "pcreate -s pyramid_jinja2_starter xyz". Was it Pyramid or pyramid_jinja2 that changed?
Creating a Jinja2 Pyramid Project¶
at this url: http://docs.pylonshq.com/pyramid_jinja2/dev/
i think the command should read as follows:
$ paster create -t pyramid_jinja2_starter
but it reads as:
$ paster create -t bin/paster pyramid_jinja2_starter
The warning:
DeprecationWarning: reload_templates setting is deprecated, use pyramid.reload_templates instead.
is displayed for me whenever I run my nosetests suite for my project which uses pyramid_jinja2
. For a while I thought this was telling me that I needed to update my configuration, but I couldn't find any trace of the old setting.
It appears that this message is displayed even if the user doesn't use this setting, because Pyramid itself sets this setting, presumably for backwards compatibility with stuff that looks for it (see this line of code in pyramid/config/settings.py).
I propose to remove the warning, since it will be displayed even when the user cannot do anything about it. Unless someone can figure out a way to determine whether the setting came from Pyramid or from a user app, but I don't see a way to do this.
I will send a PR.
can we have a complete example how to add variables and functions to jinja's Environment.globals?
I am using google appengine with pyramid, and tried to use jinja2.
When I add config.include('pyramid_jinja2') it crashes in some introspect code ...
in _get_or_build_default_environment(config.registry)
It seems to crash in python's inspect.py
Someone else had this error too:
http://stackoverflow.com/questions/8031476/pyramid-jinja2-and-new-gae-runtime
It can be fixed by creating a VirtualModule main which means patching init.py of every new release of pyramid_jinja2, see comment below.
main.py ...
import os
import logging
logging.getLogger().setLevel(logging.DEBUG)
from pyramid.config import Configurator
from yaml import load
from appglobals import APP_BASE_DIR
SETTINGS_FILE = os.path.join(APP_BASE_DIR, 'settings.yaml')
def app_config():
config = Configurator(settings=load(open(SETTINGS_FILE, 'r').read()))
config.add_settings({'locandy.appbasedir': APP_BASE_DIR})
config.hook_zca()
config.include('pyramid_jinja2')
config.add_route('catchall', '{notfound:.*}')
return config
config = app_config()
application = config.make_wsgi_app()
Traceback (most recent call last):
File "/Users/cat/repositories/locandy-web/parts/appengine_sdk/google/appengine/runtime/wsgi.py", line 196, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/Users/cat/repositories/locandy-web/parts/appengine_sdk/google/appengine/runtime/wsgi.py", line 255, in _LoadHandler
handler = import(path[0])
File "/Users/cat/repositories/locandy-web/app/main.py", line 22, in
config = app_config()
File "/Users/cat/repositories/locandy-web/app/main.py", line 18, in app_config
config.include('pyramid_jinja2')
File "distlib/pyramid/config/init.py", line 773, in include
c(configurator)
File "distlib/pyramid_jinja2/init.py", line 468, in includeme
_get_or_build_default_environment(config.registry)
File "distlib/pyramid_jinja2/init.py", line 252, in _get_or_build_default_environment
package = _caller_package(('pyramid_jinja2', 'jinja2', 'pyramid.config'))
File "distlib/pyramid_jinja2/init.py", line 132, in caller_package
for t in self.inspect.stack():
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 1054, in stack
return getouterframes(sys._getframe(1), context)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 1032, in getouterframes
framelist.append((frame,) + getframeinfo(frame, context))
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 1007, in getframeinfo
lines, lnum = findsource(frame)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 532, in findsource
module = getmodule(object, file)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 504, in getmodule
main = sys.modules['main']
KeyError: 'main'
It's not currently possible to define more than one jinja2 renderer unless they share the same settings. There's also threading issues if pyramid_jinja2 isn't included and the global renderer_factory
is registered to another file extension instead. The config directives are very much based around this idea as well, where add_jinja2_search_path, get_jinja2_environment and add_jinja2_extension all work on the app-global jinja2 environment.
I'd like to fix these issues if you guys are amenable as its something I need and much better going forward if jinja2 is used in multiple addons. For example, I recently solved these problems in pyramid_mako to make it simpler for the pyramid_debugtoolbar to use custom mako settings on its own templates, without affecting your app's configuration.
As far as these fixes affect the current api, I think you'd want to update them to take an optional extension argument which would default to '.jinja2'. Ideally you'd just deprecate/get rid of them because I think the renderers should be fully-configurable through the settings, but adding the discriminator in the signatures would be the next best thing.
For consistency with Pyramid 1.5.8 and 1.6.
This is a very minor point. Pyramid changed its jargon from "models" to "resources".
I bring this up because I am writing some new, official Getting Started docs for Pyramid. I'm considering basing the templating part on pyramid_jinja2. As such, I'd like beginners to avoid confusion, which might lead to some other tickets.
Hi,
I use Pyramid and pyramid_jinja2 in my project.
I need to use a personal Jinja2 template template.
I've saw I can register an IJinja2Environment utility.
environment = registry.queryUtility(IJinja2Environment)
In my project, I would like create a "environment" almost identical than
environment declaration of "pyramid_jinja2.renderer_factory" :
reload_templates = settings.get('reload_templates', False)
directories = settings.get('jinja2.directories')
...
environment = Environment(loader=loader,
auto_reload=reload_templates,
autoescape=autoescape,
extensions=extensions)
environment.filters.update(filters)
Personnaly, I would like the same think but I would like customize the "loader".
To make this, if I register one IJinja2Environment utility I've one problem, in utility I haven't access to settings then I can't do :
reload_templates = settings.get('reload_templates', False)
...
filters = settings.get('jinja2.filters', '')
This is my suggestion in "pyramid_jinja2.renderer_factory" function :
def renderer_factory(info):
registry = info.registry
settings = info.settings
environment = registry.queryUtility(IJinja2Environment)
if environment is None:
environment_factory = registry.queryUtility(IJinja2EnvironmentFactory)
if environment_factory 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)
else:
environment = environment_factory(info)
registry.registerUtility(environment, IJinja2Environment)
return Jinja2TemplateRenderer(info, environment)
With this "patch" I can register a IJinja2EnvironmentFactory utility, in this
factory I have access to "registry" and "settings" via "info" parameter.
What do you think about this suggest ? Do you have others solutions / ideas ?
Regards,
Stephane
I am trying to use pyramid_webassets and pyramid_jinja2 together. My main function looks like this.
def main(global_config, **settings):
engine = engine_from_config(settings, 'sqlalchemy.', encoding='utf-8')
get_root = appmaker(engine)
session_factory = session_factory_from_settings(settings)
config = Configurator(settings=settings, root_factory=get_root)
config.include('pyramid_handlers')
# Jinja2
config.include('pyramid_jinja2')
config.add_jinja2_renderer('.html')
config.add_jinja2_search_path('shared_templates:templates', name='.html')
config.add_jinja2_search_path('myapp:templates', name='.html')
# Webassets
config.include('pyramid_webassets')
config.add_jinja2_extension('webassets.ext.jinja2.AssetsExtension')
assets_env = config.get_webassets_env()
jinja2_env = config.get_jinja2_environment() # is None ???
jinja2_env.assets_environment = assets_env
...
The error I get is AttributeError: 'NoneType' object has no attribute 'assets_environment'
http://docs.pylonshq.com/pyramid_jinja2/dev/
from pyramid_jinja2 import renderer_factory
config.add_renderer(.'jinja2', renderer_factory)
should be
from pyramid_jinja2 import renderer_factory
config.add_renderer('.jinja2', renderer_factory)
With
reload_templates = true
set in development.ini, the value is verified as being true prior to:
lib/python2.6/site-packages/pyramid_jinja2-0.1-py2.6.egg/pyramid_jinja2/init.py:
environment = Environment(loader=loader, auto_reload=reload_templates,
autoescape=True)
However, modifications made to templates are not reflected until pyramid is restarted.
The GetText callables installed by pyramid_jinja2 do not honor the request given to the render function but always use the global request instead.
While the existence of a global request is an acceptable default, the Jinja2 renderer should prefer an explicit request whenever it is provided. Calling it like so:
from pyramid.renderers import render
request = DummyRequest(...)
assert request.locale_name == 'es'
render('some.jinja2', dict(), request=request)
Then the locale from get_current_request()
will be used instead of the one explicitly specified.
I’d like to use Jinja2>=2.7. Since 6ee506c, however this produces a VersionConflict exception. I’m not running python 3.2 and so do not care about py3.2 compatibility.
This may be a bad idea, but could the pinning be made conditional on interpreter version? I mean by doing something like this in setup.py
if (3,) < sys.version_info < (3,3):
requires..extend([
'Jinja2>=2.5.0,<2.7dev', #2.7 drops Python 3.2 compat.
'markupsafe<0.16', #0.16 drops Python 3.2 compat
])
else:
requires..extend([
'Jinja2>=2.5.0',
'markupsafe',
])
Or is there a better way for me to deal with this on my end? (Right now I’m pinning pyramid_jinja2<1.7
.)
if I do $ paster create -t pyramid_jinja2_starter
Near the top of the sample template I get:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:tal="http://xml.zope.org/namespaces/tal">
I can't make Jinja2 2.8 work with Pyramid 1.4.2 and Python 3.3.2. I got this error:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/waitress-0.8.5-py3.3.egg/waitress/channel.py", line 332, in service
task.service()
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/waitress-0.8.5-py3.3.egg/waitress/task.py", line 174, in service
self.execute()
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/waitress-0.8.5-py3.3.egg/waitress/task.py", line 382, in execute
app_iter = self.channel.server.application(env, start_response)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pyramid-1.4.2-py3.3.egg/pyramid/router.py", line 251, in __call__
response = self.invoke_subrequest(request, use_tweens=True)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pyramid-1.4.2-py3.3.egg/pyramid/router.py", line 227, in invoke_subrequest
response = handle_request(request)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pyramid-1.4.2-py3.3.egg/pyramid/tweens.py", line 21, in excview_tween
response = handler(request)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pyramid_tm-0.7-py3.3.egg/pyramid_tm/__init__.py", line 82, in tm_tween
reraise(*exc_info)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pyramid_tm-0.7-py3.3.egg/pyramid_tm/compat.py", line 13, in reraise
raise value
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pyramid_tm-0.7-py3.3.egg/pyramid_tm/__init__.py", line 63, in tm_tween
response = handler(request)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pyramid-1.4.2-py3.3.egg/pyramid/router.py", line 161, in handle_request
response = view_callable(context, request)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pyramid-1.4.2-py3.3.egg/pyramid/config/views.py", line 369, in rendered_view
context)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pyramid-1.4.2-py3.3.egg/pyramid/renderers.py", line 531, in render_view
return self.render_to_response(response, system, request=request)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pyramid-1.4.2-py3.3.egg/pyramid/renderers.py", line 561, in render_to_response
result = self.render(value, system_values, request=request)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pyramid-1.4.2-py3.3.egg/pyramid/renderers.py", line 557, in render
result = renderer(value, system_values)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pyramid_jinja2-1.6-py3.3.egg/pyramid_jinja2/__init__.py", line 385, in __call__
return self.template.render(system)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pyramid_jinja2-1.6-py3.3.egg/pyramid_jinja2/__init__.py", line 371, in template
return self.environment.get_template(name)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/Jinja2-2.8_devdev_20130604-py3.3.egg/jinja2/environment.py", line 791, in get_template
return self._load_template(name, self.make_globals(globals))
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/Jinja2-2.8_devdev_20130604-py3.3.egg/jinja2/environment.py", line 765, in _load_template
template = self.loader.load(self, name, globals)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/Jinja2-2.8_devdev_20130604-py3.3.egg/jinja2/loaders.py", line 119, in load
bucket = bcc.get_bucket(environment, name, filename, source)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/Jinja2-2.8_devdev_20130604-py3.3.egg/jinja2/bccache.py", line 176, in get_bucket
key = self.get_cache_key(name, filename)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/Jinja2-2.8_devdev_20130604-py3.3.egg/jinja2/bccache.py", line 163, in get_cache_key
if isinstance(filename, unicode):
NameError: global name 'unicode' is not defined
I have WebOb 1.2.3 and distribute 0.6.45. Thanks!!!
Calling config.add_jinja2_extension("extension")
will unregister the existing Jinja2 enviornment and recreate it from scratch, killing all the changes that may have happened to the environment, such as added filters or other gettext callables. This is rather unexpected and does not even create any log output, which makes this very hard to spot.
I'm using jinja2 templates dynamically in pyramid. It works fine for basic usage, but it fails when trying to load internationalized text with the GETTEXT() function:
@view_config(context=Test)
def test_view(request):
#Render templates dynamically:
template = "template1.jinja2"
return Response(render(template, {'test1':1}, request=request))
Basic jinja2 template:
<!-- template/template1.jinja2 -->
{{ GETTEXT('NAME') }} - {{ test1 }}
Throws the following error:
File "/python3.4/site-packages/pyramid/i18n.py", line 218, in get_localizer
return request.localizer
AttributeError: 'NoneType' object has no attribute 'localizer'
I've tracked the error, it seems to be a problem on file pyramid_jinja2/i18n.py when the function localizer() is calling i18n.get_localizer(get_current_request()), but the function get_current_request() generates a None value. So it's not being able to create a valid Request.
class GetTextWrapper(object):
....
@property
def localizer(self):
return i18n.get_localizer(get_current_request())
....
I just recently added the ability for pyramid_mako to use caller-relative template lookup. I did it in a bw-compat way by deferring to the current search path-based lookup if mako.directories is defined. If it is not, then the template is looked up relative to the place in which the template is requested (this is how chameleon works all the time). Imagine:
@view_config(renderer='templates/foo.jinja2')
def myview(request):
return {}
Are you open to a pull request adding this functionality to jinja2?
With the release of Pyramid 1.7, we've switched from nose and coverage to py.test and pytest-cov, and have added default configuration for both. We've also switched from easy_install to pip.
See:
Hi!
I just tried to use the jinja2 loader in the same way as I do for the chameleon loader where it is able to find the assets relative to the current module's path but it didn't work.
Inspecting the source code I could figure a solution but I am not sure if this is a good solution, I'm submitting here for review. Once I have more time I will try to make some tests and send a pull request.
This is what the new Jinja2TemplateRenderer class looks like:
class Jinja2TemplateRenderer(object):
'''Renderer for a jinja2 template'''
template = None
def __init__(self, info, environment):
self.info = info
self.environment = environment
def implementation(self):
return self.template
@property
def template(self):
name = self.info.name
name_with_package = name
package = self.info.package
if ':' not in name:
name_with_package = '%s:%s' % (package.__name__, name)
try:
return self.environment.get_template(self.info.name)
except TemplateNotFound:
return self.environment.get_template(name_with_package)
def __call__(self, value, system):
try:
system.update(value)
except (TypeError, ValueError):
ex = sys.exc_info()[1] # py2.5 - 3.2 compat
raise ValueError('renderer was passed non-dictionary '
'as value: %s' % str(ex))
return self.template.render(system)
Jinja2 has custom filters and extensions.
To adding custom filter, we need accessing filters attribute of environ.
Extensions are added in the environ constructor.
For some reason the root factory takes an environ
instead of a request
? It's not used, but it's deceiving.
I noticed that some of the links in mytemplate.jinja2 are broken i version 1.2. How about keeping branches for older versions of pyramid_jinja2 to be able to patch older versions?
The paster template has gotten behind from the pyramid trunk. It doesn't include a production.ini, MANIFEST.in, setup.cfg, etc.
versions: Python 3.5.0, Pyramid: v1.6
http://docs.pylonsproject.org/projects/pyramid-jinja2/en/latest/ -> 404
(env) docs > make html
cd ..; git submodule update --init --recursive; cd docs;
mkdir -p _build/html _build/doctrees
sphinx-build -b html -d _build/doctrees -W . _build/html
Running Sphinx v1.3.1
loading pickled environment... not yet created
loading intersphinx inventory from http://docs.pylonsproject.org/projects/translationstring/en/latest/objects.inv...
loading intersphinx inventory from http://docs.sqlalchemy.org/en/latest/objects.inv...
loading intersphinx inventory from http://docs.python.org/objects.inv...
loading intersphinx inventory from http://docs.pylonsproject.org/projects/pyramid-jinja2/en/latest/objects.inv...
Warning, treated as error:
WARNING: intersphinx inventory 'http://docs.pylonsproject.org/projects/pyramid-jinja2/en/latest/objects.inv' not fetchable due to <class 'urllib.error.HTTPError'>: HTTP Error 404: OK
make: *** [html] Error 1
also in few other projects have 404, for example:
http://docs.pylonsproject.org/projects/pyramid-zcml/en/latest/
Thanks for an advice
System:
Darwin 10.7.0 Darwin Kernel Version 10.7.0: Sat Jan 29 15:17:16 PST 2011; root:xnu-1504.9.37~1/RELEASE_I386 i386
Packages: (with version)
Babel-0.9.6
Jinja2-2.5.5
pyramid_jinja2-0.6.2
development.ini:
...
default_locale_name = ro
jinja2.directories = templates
...
init.py:
...
config.include('pyramid_jinja2')
...
views.py: (later explanation)
def index(request):
print get_localizer(request).translate(_('Subscription form'))
templates/register.jinja2:
...
{% trans %}Subscription form{% endtrans %}
...
Issue:
When the index() function from views.py gets called, it prints the translated string (from locale/ro/LC_MESSAGES/...), however, when i render the template, 'Subscription form' doesn't get translated at all.
I also have added jinja2.ext.i18n to jinja2.extensions in development.ini, however, it still won't translate my strings.
What am i doing wrong?
Currently i'm use monkey patch:
#######################
import pyramid_jinja2
from pyramid.path import AssetResolver
def aspec(template, pname='__name__'):
return AssetResolver().resolve(template).abspath()
pyramid_jinja2.abspath_from_asset_spec = aspec
Howdy, @mmerickel @domenkozar @rockyburt or @mcdonc
I've updated the scaffold to be consistent with Pyramid's default scaffolds in PR #116, and updated changes.txt. I'd like to push a release to PyPI. Is there anything I can do to help?
On Python3, using pyramid_jinja2 2.5, while setting jinja2.i18n.gettext
I hit the following error:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/pyramid/config/__init__.py", line 1059, in execute_actions
callable(*args, **kw)
File "/usr/lib/python3/dist-packages/pyramid_jinja2/__init__.py", line 440, in register
package,
File "/usr/lib/python3/dist-packages/pyramid_jinja2/settings.py", line 134, in parse_env_options_from_settings
if not issubclass(gettext_wrapper, GetTextWrapper):
TypeError: issubclass() arg 1 must be a class
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/bin/pserve3", line 9, in <module>
load_entry_point('pyramid==1.5.1', 'console_scripts', 'pserve')()
File "/usr/lib/python3/dist-packages/pyramid/scripts/pserve.py", line 51, in main
return command.run()
File "/usr/lib/python3/dist-packages/pyramid/scripts/pserve.py", line 316, in run
global_conf=vars)
File "/usr/lib/python3/dist-packages/pyramid/scripts/pserve.py", line 340, in loadapp
return loadapp(app_spec, name=name, relative_to=relative_to, **kw)
File "/usr/lib/python3/dist-packages/paste/deploy/loadwsgi.py", line 247, in loadapp
return loadobj(APP, uri, name=name, **kw)
File "/usr/lib/python3/dist-packages/paste/deploy/loadwsgi.py", line 272, in loadobj
return context.create()
File "/usr/lib/python3/dist-packages/paste/deploy/loadwsgi.py", line 710, in create
return self.object_type.invoke(self)
File "/usr/lib/python3/dist-packages/paste/deploy/loadwsgi.py", line 146, in invoke
return fix_call(context.object, context.global_conf, **context.local_conf)
File "/usr/lib/python3/dist-packages/paste/deploy/util.py", line 55, in fix_call
val = callable(*args, **kw)
File "/opt/olfeo/lib/python3.4/site-packages/stats_gui/main.py", line 56, in main
return config.make_wsgi_app()
File "/usr/lib/python3/dist-packages/pyramid/config/__init__.py", line 939, in make_wsgi_app
self.commit()
File "/usr/lib/python3/dist-packages/pyramid/config/__init__.py", line 610, in commit
self.action_state.execute_actions(introspector=self.introspector)
File "/usr/lib/python3/dist-packages/pyramid/config/__init__.py", line 1067, in execute_actions
tb)
File "/usr/lib/python3/dist-packages/pyramid/compat.py", line 131, in reraise
raise value.with_traceback(tb)
File "/usr/lib/python3/dist-packages/pyramid/config/__init__.py", line 1059, in execute_actions
callable(*args, **kw)
File "/usr/lib/python3/dist-packages/pyramid_jinja2/__init__.py", line 440, in register
package,
File "/usr/lib/python3/dist-packages/pyramid_jinja2/settings.py", line 134, in parse_env_options_from_settings
if not issubclass(gettext_wrapper, GetTextWrapper):
pyramid.exceptions.ConfigurationExecutionError: <class 'TypeError'>: issubclass() arg 1 must be a class
in:
Line 482 of file /usr/lib/python3/dist-packages/pyramid_jinja2/__init__.py:
config.add_jinja2_renderer('.jinja2', package=package)
I think this is a bug. I am willing to help. Meanwhile can someone provide a wordaround?
Thanks
I have a pretty standard Pyramid stack which is using jinja2 and Babel for the localisation. Problem with it, translation is working when using the direct call to the gettext function like that:
{{ _("my string") }}
But just silently failed when using the {% trans %} tags.
The documentation doesn't mention anything about the trans tags specifically but it seems something is not handled properly with the default configuration.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.