How to use the jinja.Environment function in Jinja

To help you get started, we’ve selected a few Jinja examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sphinx-doc / sphinx / sphinx / _jinja.py View on Github external
def init(self, builder):
        self.templates = {}
        base_templates_path = path.join(path.dirname(__file__), 'templates')
        ext_templates_path = [path.join(builder.confdir, dir)
                              for dir in builder.config.templates_path]
        self.templates_path = [base_templates_path] + ext_templates_path
        loader = SphinxFileSystemLoader(base_templates_path, ext_templates_path)
        if builder.translator is not None:
            self.jinja_env = TranslatorEnvironment(loader=loader,
                    friendly_traceback=False, translator=builder.translator)
        else:
            self.jinja_env = Environment(loader=loader,
                    # disable traceback, more likely that something
                    # in the application is broken than in the templates
                    friendly_traceback=False)
github pallets / jinja / jdebug.py View on Github external
:license: BSD, see LICENSE for more details.
"""
import os
import sys
import gc
from jinja import Environment
from jinja.parser import Parser
from jinja.lexer import Lexer
from jinja.translators.python import PythonTranslator


__all__ = ['e', 't', 'p', 'l', 'm']


_global_frame = sys._getframe()
e = Environment()
t = e.from_string


def p(x=None, f=None):
    if x is None and f is not None:
        x = e.loader.get_source(f)
    print PythonTranslator(e, Parser(e, x, f).parse(), None).translate()

def l(x):
    for item in e.lexer.tokenize(x):
        print '%5s  %-20s  %r' % (item.lineno,
                                  item.type,
                                  item.value)

class MemoryGuard(object):
github sphinx-doc / sphinx / sphinx / _jinja.py View on Github external
filename = name
        else:
            for searchpath in self.searchpaths:
                if path.exists(path.join(searchpath, name)):
                    filename = path.join(searchpath, name)
                    break
            else:
                raise TemplateNotFound(name)
        f = codecs.open(filename, 'r', environment.template_charset)
        try:
            return f.read()
        finally:
            f.close()


class TranslatorEnvironment(Environment):
    class _Translator(object):
        def __init__(self, translator):
            self.trans = translator

        def gettext(self, string):
            return self.trans.ugettext(string)

        def ngettext(self, singular, plural, n):
            return self.trans.ungettext(singular, plural, n)

    def __init__(self, *args, **kwargs):
        self.translator = kwargs['translator']
        del kwargs['translator']
        super(TranslatorEnvironment, self).__init__(*args, **kwargs)

    def get_translator(self, context):
github pallets / jinja / docs / generate.py View on Github external
for loader in loaders:
        doclines = []
        for line in inspect.getdoc(loader).splitlines():
            doclines.append('    ' + line)
        result.append('`%s`\n%s' % (loader.__name__, '\n'.join(doclines)))

    return '\n\n'.join(result)

def generate_environment_doc():
    from jinja.environment import Environment
    return '%s\n\n%s' % (
        inspect.getdoc(Environment),
        inspect.getdoc(Environment.__init__)
    )

e = Environment()

PYGMENTS_FORMATTER = HtmlFormatter(style='pastie', cssclass='syntax')

LIST_OF_FILTERS = generate_list_of_filters()
LIST_OF_TESTS = generate_list_of_tests()
LIST_OF_LOADERS = generate_list_of_loaders()
LIST_OF_BASELOADERS = generate_list_of_baseloaders()
ENVIRONMENT_DOC = generate_environment_doc()
CHANGELOG = file(os.path.join(os.path.dirname(__file__), os.pardir, 'CHANGES'))\
            .read().decode('utf-8')

FULL_TEMPLATE = e.from_string('''\


github TurboGears / tg2 / tg / environment.py View on Github external
def template_loaded(template):
                "Plug-in our i18n function to Genshi."
                genshi.template.filters.insert(0, Translator(ugettext))
                
            config['pylons.app_globals'].genshi_loader = TemplateLoader(
                paths['templates'], auto_reload=True)
            
            config['pylons.app_globals'].renderer_functions = render_genshi  
                
        if 'jinja' in base_config.renderers:
            # Create the Jinja Environment
            from jinja import ChoiceLoader, Environment, FileSystemLoader
            from tg.render import render_jinja
            
            config['pylons.app_globals'].jinja_env = Environment(loader=ChoiceLoader(
                    [FileSystemLoader(path) for path in paths['templates']]))
            # Jinja's unable to request c's attributes without strict_c
            config['pylons.strict_c'] = True
            
            config['pylons.app_globals'].renderer_functionsloa = render_jinja
        
        # If you'd like to change the default template engine used to render
        # text/html content, edit these options.
        config['buffet.template_engines'].pop()
        template_location = '%s.templates' %base_config.package.__name__
        config.add_template_engine(base_config.default_renderer, 
                                   template_location,  {})

        if base_config.use_sqlalchemy:  
            # Setup SQLAlchemy database engine
            from sqlalchemy import engine_from_config
github pallets / werkzeug / docs / generate.py View on Github external
import inspect
from datetime import datetime
from cgi import escape

from docutils import nodes
from docutils.parsers.rst import directives
from docutils.core import publish_parts
from docutils.writers import html4css1

from jinja import Environment

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter

e = Environment()

PYGMENTS_FORMATTER = HtmlFormatter(style='pastie', cssclass='syntax')

FULL_TEMPLATE = e.from_string('''\



  <title>{{ title }} — Werkzeug Documentation</title>
  
  
  <style type="text/css">
    {{ style|e }}
  </style>

github pallets / jinja / jinja2 / contrib / _djangosupport.py View on Github external
global env

    if env:
        warnings.warn("Jinja already initialized.")
        return

    # setup environment
    if loader is None:
        loaders = tuple(FileSystemLoader(l) for l in settings.TEMPLATE_DIRS)
        if not loaders:
            loader = None
        elif len(loaders) == 1:
            loader = loaders[0]
        else:
            loader = ChoiceLoader(loaders)
    env = Environment(loader=loader, **options)

    # convert requested filters
    for name in convert_filters:
        env.filters[name] = convert_django_filter(name)

    # import templatetags of installed apps
    for app in settings.INSTALLED_APPS:
        try:
            __import__(app + '.templatetags')
        except ImportError:
            pass

    # setup the django.contrib.jinja module
    setup_django_module()