How to use the jinja2.PackageLoader function in Jinja2

To help you get started, we’ve selected a few Jinja2 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 datafolklabs / cement / cement / ext / ext_jinja2.py View on Github external
tuple: The content of the template (``str``), the type of template
            (``str``: ``directory``, or ``module``), and the path (``str``) of
            the directory or module)

        Raises:
            cement.core.exc.FrameworkError: If the template does not exist in
                either the ``template_module`` or ``template_dirs``.
        """
        content, _type, _path = super(Jinja2TemplateHandler, self).load(*args,
                                                                        **kw)

        if _type == 'directory':
            self.env.loader = FileSystemLoader(self.app._meta.template_dirs)
        elif _type == 'module':
            parts = self.app._meta.template_module.rsplit('.', 1)
            self.env.loader = PackageLoader(parts[0], package_path=parts[1])

        return content, _type, _path
github howie6879 / Sanic-For-Pythoneer / examples / demo06 / sample / src / views / rss_html.py View on Github external
from jinja2 import Environment, PackageLoader, select_autoescape
from sanic import Blueprint
from sanic.response import html

from src.config import CONFIG

# https://github.com/channelcat/sanic/blob/5bb640ca1706a42a012109dc3d811925d7453217/examples/jinja_example/jinja_example.py
# 开启异步特性  要求3.6+
enable_async = sys.version_info >= (3, 6)

html_bp = Blueprint('rss_html', url_prefix='html')
html_bp.static('/statics/rss_html', CONFIG.BASE_DIR + '/statics/rss_html')

# jinjia2 config
env = Environment(
    loader=PackageLoader('src.views.rss_html', '../templates/rss_html'),
    autoescape=select_autoescape(['html', 'xml', 'tpl']),
    enable_async=enable_async)


async def template(tpl, **kwargs):
    template = env.get_template(tpl)
    rendered_template = await template.render_async(**kwargs)
    return html(rendered_template)

@html_bp.route("/")
async def index(request):
    return await template('index.html')

@html_bp.route("/index")
async def rss_html(request):
    url = "http://blog.howie6879.cn/atom.xml"
github dials / dials / algorithms / scaling / observers.py View on Github external
def make_scaling_html(self, scaling_script):
        """Collect data from the individual observers and write the html."""
        html_file = scaling_script.params.output.html
        json_file = scaling_script.params.output.json
        if not (html_file or json_file):
            return
        self.data.update(ScalingModelObserver().make_plots())
        self.data.update(ScalingOutlierObserver().make_plots())
        self.data.update(ErrorModelObserver().make_plots())
        self.data.update(MergingStatisticsObserver().make_plots())
        self.data.update(FilteringObserver().make_plots())
        if html_file:
            logger.info("Writing html report to: %s", html_file)
            loader = ChoiceLoader(
                [
                    PackageLoader("dials", "templates"),
                    PackageLoader("dials", "static", encoding="utf-8"),
                ]
            )
            env = Environment(loader=loader)
            template = env.get_template("scaling_report.html")
            html = template.render(
                page_title="DIALS scaling report",
                scaling_model_graphs=self.data["scaling_model"],
                scaling_tables=self.data["scaling_tables"],
                resolution_plots=self.data["resolution_plots"],
                scaling_outlier_graphs=self.data["outlier_plots"],
                error_model_plots=self.data["error_model_plots"],
                anom_plots=self.data["anom_plots"],
                batch_plots=self.data["batch_plots"],
                misc_plots=self.data["misc_plots"],
                filter_plots=self.data["filter_plots"],
github frappe / frappe / frappe / __init__.py View on Github external
def get_jloader():
	if not local.jloader:
		from jinja2 import ChoiceLoader, PackageLoader

		apps = get_installed_apps()
		apps.remove("frappe")
	
		local.jloader = ChoiceLoader([PackageLoader(app, ".") \
				for app in apps + ["frappe"]])
				
	return local.jloader
github CSCfi / pebbles / pebbles / tasks / misc_tasks.py View on Github external
def send_mails(users, text=None):
    """ ToDo: document. apparently sends activation emails.
    """
    dynamic_config = get_dynamic_config()
    j2_env = jinja2.Environment(loader=jinja2.PackageLoader('pebbles', 'templates'))
    base_url = dynamic_config['BASE_URL'].strip('/')
    # Here email_id is used to send email because sending emails through eppn might not work in some cases
    for email_id, token, user_active in users:
        if text is None:
            activation_url = '%s/#/activate/%s' % (base_url, token)
            msg = MIMEText(j2_env.get_template('invitation.txt').render(activation_link=activation_url, instance_name=dynamic_config['INSTALLATION_NAME'], instance_description=dynamic_config['INSTALLATION_DESCRIPTION'], user_active=user_active))
            subject = '%s account activation' if not user_active else '%s password reset'
            msg['Subject'] = subject % dynamic_config['INSTALLATION_NAME']
        else:
            msg = MIMEText(text['message'])
            subject = text['subject'] + " - %s"
            msg['Subject'] = subject % dynamic_config['INSTALLATION_NAME']
        msg['To'] = email_id
        msg['From'] = dynamic_config['SENDER_EMAIL']
        logger.info(msg)
github Juniper / OpenClos / jnpr / openclos / writer.py View on Github external
def __init__(self, conf, pod, dao):
        WriterBase.__init__(self, conf, pod, dao)
        self.templateEnv = Environment(loader=PackageLoader(cablingPlanTemplatePackage, templateLocation))
        #self.templateEnv.trim_blocks = True
        self.templateEnv.lstrip_blocks = True
        self.template = self.templateEnv.get_template(self._pod.topologyType + '.json')
github zerovm / zerovm-cli / zpmlib / zapptemplate.py View on Github external
def render_zapp_yaml(name, template_name=_PYTHON_ZAPP_YAML):
    # TODO: wtf is `name`?
    """Load and render the zapp.yaml template."""
    loader = jinja2.PackageLoader('zpmlib', 'templates')
    env = jinja2.Environment(loader=loader)
    tmpl = env.get_template(template_name)
    return tmpl.render(name=name)
github praekelt / swagger-django-generator / swagger_django_generator / generator.py View on Github external
def render_to_string(backend, filename, context):
    # type: (str, str, Dict) -> str
    """
    Render a template using the specified context
    :param backend: The backend for which the template is rendered
    :param filename: The template name
    :param context: The data to use when rendering the template
    :return: The rendered template as a string
    """
    template_directory = "./swagger_django_generator/templates/{}".format(backend)
    loaders = [jinja2.FileSystemLoader(template_directory)]
    try:
        import swagger_django_generator
        loaders.append(jinja2.PackageLoader("swagger_django_generator", "templates/{}".format(backend)))
    except ImportError:
        pass

    environment = jinja2.Environment(
        loader=jinja2.ChoiceLoader(loaders),
        trim_blocks=True,
        lstrip_blocks=True,
    )
    environment.filters["clean_schema"] = clean_schema
    environment.filters["parse_array"] = parse_array

    return environment.get_template(filename).render(context)
github wrobstory / sticky / sticky / d3plus.py View on Github external
# -*- coding: utf-8 -*-
"""
D3Plus:
http://d3plus.org/
https://github.com/alexandersimoes/d3plus
"""
import json

from IPython.html import widgets
from IPython.utils.traitlets import Unicode, Int, List
from jinja2 import Environment, PackageLoader

from sticky.core import Chart


ENV = Environment(loader=PackageLoader('sticky', 'templates/d3plus'))


class d3Plus(widgets.DOMWidget, Chart):

    kind = 'd3plus'
    render_template = ENV.get_template('d3plus_widget.js')

    _view_name = Unicode('D3Plus', sync=True)
    chart_id = Unicode(sync=True)
    chart_type = Unicode(sync=True)
    model_data = Unicode(sync=True)
    model_key = List(sync=True)
    model_x = Unicode(sync=True)
    model_y = Unicode(sync=True)
    model_height = Int(sync=True)
    model_width = Int(sync=True)
github kracekumar / pythonbyexamplestutorial / august-workshop / bowl.py View on Github external
def render_template(template_name, app_name='', template_dir='', **context):
    if template_dir:
        env = Environment(loader=PackageLoader(template_dir))
    else:
        env = Environment(loader=PackageLoader('application', 'templates'))
    try:
        template = env.get_template(template_name)
    except TemplateNotFound as e:
        return Response(body="Template not found: {}".format(e),
                        status='404')
    return Response(body=template.render(**context),
                    content_type='text/html')