Load jinja2 templates dynamically on a Pyramid view - jinja2

I'm developing a Pyramid project with jinja2 templating engine. Following the jinja2 documentation I've find out a way to load different templates from a unique view. But taking into account that the module 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?

The following is enough:
from pyramid.renderers import render
template = "section/example1.jinja2"
context = dict(a=1, b=2)
body = render(template, context, request=request)
And to configure loading do in your __init__.py:
config.add_jinja2_search_path('project_name:templates', name='.jinja2', prepend=True)

Related

Can we use python related api's on the Django templates?

I am new to Django and hence not having thorough knowledge about it. So I am facing a few errors in Django.
Currently I am trying to print the type of a variable from the Django template html file as follows:
<center><h2>The type of feature list report for version {%type(version)%} is<h2></center>
For the above, I am getting the following error:
Invalid block tag on line 9: 'type(version)'. Did you forget to register or load this tag?
So what's going wrong here? How can we use the python related api's (like type(), strip(), get(), etc) from the html template files? I think inside the {% .... %} we can use python related evaluations. Am I right?
Please throw some lights on this .
As said, this is not the philosophy of DTL, but some functions that transform input are implemented as filters.
In addition, you can write your own filters and supporting a "type" filter, would be very simple:
from django import template
from typing import Any
register = template.Library()
def filter_type(value: Any) -> str:
return str(type(value))
register.filter('type', filter_type)
See the documentation for details.
Both Jinja's and DTL's approach are explicit over implicit: instead of blindly supporting any python function with all it's dangers, you have to explicitly allow it or implement it.
Running arbitrary Python code in a Django template is intentionally disabled. Aside from security concerns, the reason is your project's business logic should be separate from your presentation layer. This is part of good application design.
There are three primary ways you can call an operation from a Django template.
Pass in a function and call it.
Use a template filter, either custom or built in.
Use a template tag, either custom or built in.
Pass in a function and call it.
Calling a passed in function from a Django template is standard. However, it has two caveats.
The function must return a value that can is a string or can be coerced to a string. (Otherwise nothing will be printed in the template.)
The function must not have any required arguments.
The most common use case is either a computed value or a getter e.g.
class Page(models.Model):
title = models.CharField()
def get_title(self):
return self.title
<h1>{{ page.get_title }}</h1>
Template filters
See Melvyn's answer for an example of template filters.
Template filters operate on a value. So this is perfect for a Python function like type().
Template Tags
Edited: see Melvyn's comment.
Simple Template tags on the other hand work more like a function. They accept positional and keyword arguments and should again return a value. I won't go into inclusion tags or advanced tag compilation and rendering here, but you can read about it in the Django custom template tag docs.
Here is an example of two template tags I often include in a project in debug.py.
import pprint
from django import template
register = template.Library()
pp = pprint.PrettyPrinter(indent=4, width=120)
#register.simple_tag(takes_context=True)
def print_context(context):
pp.pprint(context)
return ""
#register.simple_tag()
def print_thing(thing):
pp.pprint(thing)
return ""
I can use print_context to print the current context in terminal and print_thing to print something.
{% load debug %}
{% print_context %}
{% print_thing 'print this string' %}
You can create a template tag that will do anything a standard Python function can do. This is because a template tag essentially calls the function you create.
Use the constraints of the Django template system to your advantage to create well designed applications where the business logic is located in the views, models, and helpers, and not in the templates.
You may create a class which includes the type, so you can call the type like: variable.type or you can send the type data from the controller.
If you need to make reactive programming logic at the front end, I'd suggest you use Vue, React or Angular.

How can I save my session or my GAN model into a js file

I want to deploy my GANs model on a web-based UI for this I need to convert my model's checkpoints into js files to be called by web code. There are functions for saved_model and Keras to convert into pb files but none for js
my main concern is that I am confused about how to dump a session or variable weights in js files
You can save a keras model from python. There is a full tutorial here but basically it amounts to calling this after training:
tfjs.converters.save_keras_model(model, tfjs_target_dir)
then hosting the result somewhere publicly accessible (or on the same server as your web UI) then you can load your model into tensorflow.js as follows:
import * as tf from '#tensorflow/tfjs';
const model = await tf.loadLayersModel('https://foo.bar/tfjs_artifacts/model.json');

rendering jinja in custom saltstack module

How to render a jinja template within a custom execution module?
I am trying to write a custom module to update confluence pages automatically. It is designed to be similar to "file.managed" call (only template source, context, and it has to respect pillar data available for given node).
can someone offer an example of pillar/context aware function call for rendering jinja template in custom module?
do the same as saltstack does in their file.managed
example :
if template:
contents = __salt__['file.apply_template_on_contents'](
contents,
template=template,
context=context,
defaults=defaults,
saltenv=__env__)

How load Jinja2 template into Environment's loader from database

FileSystemLoader loads templates from a directory, Is there anyway I could pull the template from a database as string into loader ?
env = Environment(
#loader=FileSystemLoader(templates),
loader = Filedb('template.j2') # fetch from db ?
undefined=StrictUndefined # Force variable to be defined
)
env.filters['custom_filter'] = func
t = env.get_template("template.j2")
From the Jinja docs:
If you want to create your own loader, subclass BaseLoader and override get_source.
For example:
class DatabaseLoader(BaseLoader):
def __init__(self, database_credentials):
self.database_credentials = database_credentials
def get_source(self, environment, template):
# Load from database... an exercise for the reader.
Because templates can depend on other templates, loading one template could require multiple database lookups. Database lookups could be minimized using bytecode caching to cache compiled templates.
It is also possible to load all of the templates from the database into a dictionary, and then load the dictionary using Jinja's DictLoader.

A very simple question about integrated jinja2 to pylons

I'm integrating jinja2 to pylons, I see in the document page there is:
from jinja2 import Environment, PackageLoader
config['pylons.app_globals'].jinja_env = Environment(
loader=PackageLoader('yourapplication', 'templates')
)
My question is: what should I use for yourapplication? Suppose my application is 'test', what should I write as yourapplication?
if would guess that you should use 'test' as well, like this:
config['pylons.app_globals'].jinja_env = Environment(
loader=PackageLoader('test', 'templates')
)
in general 'yourapplication' should match the name of your main applicaton package i.e. the one that contains 'config', 'controllers', 'lib' and so on)
hint: if you start on a fresh project you will be prompted for the template engine during setup, so just enter jinja2 to replace mako as default templating language and everything will be configured automatically
paster create -t pylons myapp
...
Enter template_engine (mako/genshi/jinja2/etc: Template language) ['mako']: