A very simple question about integrated jinja2 to pylons - integration

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']:

Related

Can packer use a vsphere template and extend it

I have several images I build in packer for vsphere. You can think of these as base images, like a base linux, and base windows that have minimal required software installed. I then want to have additional images which will be built from the base template and have additional services installed for example
windows_template: base image with some mandatory software
serviceA_template: extends base template but with additional services for service A
serviceB_template: extends base template but with additional services for service B
Is that possible in packer? that I can use a template name as the source instead of having to build again from ISo and install all the minimal software dependencies.
You can use the vsphere-clone builder for this. After your base build produces a VSphere template, you can then use that output artifact as the source for the child Packer template build:
source "vsphere-clone" "this" {
communicator = "none"
host = "esxi-1.vsphere65.test"
insecure_connection = "true"
password = "jetbrains"
template = "alpine" # output base build template specified here
username = "root"
vcenter_server = "vcenter.vsphere65.test"
vm_name = "alpine-clone-${local.timestamp}"
}

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.

Cakephp 3: React/zmq library namespace

I am working on on the basic tutorial on using ratchet mentioned here http://socketo.me/docs/push.
I have created a test setup for the tutorial that works flawlessly. However, when I am trying to integrate the setup with CakePHP 3 I am running into problems. The ratchet and ZMQ servers are independent just the way mentioned in the tutorial. Only the following piece of code needs to move into CakePHP 3 controllers:
$context = new ZMQContext();
$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher');
$socket->connect("tcp://localhost:5555");
$socket->send(json_encode($entryData));
This code basically submits new data to ZMQ queue for forwarding to ratchet. If I place the same 4 lines in a plain PHP file outside CakePHP 3 codebase it works. When I place the same four lines inside APP\Controller\SamplesController it says the class APP\Controller\ZMQContext not found.
CakePHP 3 docs mention that vendor libraries installed via composer will be automatically available through autoloader. I have installed React\ZMQ library via following command:
php composer require react/zmq
I have tried accessing the class via following namespaces but none of them have worked:
ZMQContext ( Class 'App\Controller\ZMQContext' not found )
\ZMQContext ( Class 'App\Controller\ZMQ' not found )
React\ZMQ\ZMQContext ( Class 'App\Controller\React\ZMQ\ZMQContext' not found )
\React\ZMQ\ZMQContext ( Class 'React\ZMQ\ZMQContext' not found )
Probably missing out on some namespace concept in PHP but my understanding is that if ZMQContext is available in a normal PHP file through global namespace, then it should also be available within CakePHP 3 via \ZMQContext.
I have following questions:
How can I push data to ZMQ Queue within my CakePHP 3 APP ?
APP::path() & APP::classname() seems to work only for classes within the CakePHP 3 application. How to check path for a particular vendor library class ?
How to autoload vendor library classes correctly ? (I do not wish to require/require_once them as it will needed to be done for each controller that wants to publish data via ratchet)
Is the assumption about accessing global namespace via \CLASSNAME wrong ?
My second attempt at accessing vendor library class at \ZMQContext resolved to App\Controller\ZMQ. How is that possible when it should have attempted within root namespace ?
ZMQContext is not part of react/zmq library so does it mean it part of default php bindings for libzmq ?
This was a simple typo problem:
$context = new \ZMQContext();
$socket = $context->getSocket(\ZMQ::SOCKET_PUSH, 'my pusher');
$socket->connect("tcp://localhost:5555");
$socket->send(json_encode($entryData));
The second namespace specification in second line was missing.

Yii2 best practices translating dynamic content

Can anyone share own experience and best practices implementing multilingual sites with Yii2? I want translate user input that is stored in database. For example article, that may have its name in three different languages, body and some translatable attributes as well.
Does Yii2 have built in features to translate the dynamic content? Or should I use third party extensions like these ones below:
https://github.com/creocoder/yii2-translateable
https://github.com/LAV45/yii2-translated-behavior
https://github.com/lajax/yii2-translate-manager
Your help would be appreciated.
Well, I can give you my point of view only based on what I have done.
There are to places to work translation
The non dynamic strings managed with i18n and messages system from
yii, that will help you with static content.
Working the translated routes dynamically with a bootstrapped class, that allows you to build this routs when the app is built.
And working with tables that have columns that support the translation like 'title_en, title_es', and as many as you need to translate. Actually in your admin interface you may want to use something like yandex to help you translating the content to this fields.
Now I will explain:
The i18n Message Translation is based on translating strings in your views, models, and in some cases like on the bootstrapped class.
You will en using Yii::t('app/main', 'Your name is {0}' as an example to translate strings that are stored on message php files.
Now if you translate stings you will want to translate the routes so you will en with routes like /articles and /articulos when you change the language.
for this purpose you will like to build a class that implements BootstrapInterface and that will be called from the process of bootstrapping your app.
So this is an example of my settings.php that I use for this
namespace app\base;
use Yii;
use yii\base\BootstrapInterface;
class settings implements BootstrapInterface {
public function __construct() { }
public function bootstrap($app) {
/// Dynamic translated routes
$t_articles = Yii::t('app/route', 'articles');
$app->getUrlManager()->addRules([
'/'.$t_articles => '/articles',
], false);
}
}
And remember to bootstrap the class in your config file «i.e. web.php»
'bootstrap' => [
'log',
'app\base\settings',
],
And finally to translate text from the database you may want to make a table that supports the translated text like:
CREATE TABLE articles (
id INT,
title_en VARCHAR(20),
title_es VARCHAR(20)
);
So when you call your app you can pull your data using something like the following on the action (only a simple example):
$articles = ArticlesA::find()->where(['id' => 1])->one();
$lang = $this->module->language;
return $thi
s->render('index',['articles'=>$articles, 'lang'=>$lang]);
or in the view as:
<p class="lead"><?=$articles['title_'.$lang]?></p>
I hope this explains the way I have been translating my apps.
Use a Google translator API or Yandex API to for smooth translations for multiple languages.
Few links that i have found on git
https://github.com/borodulin/yii2-i18n-google
Tutorial
RichWeber/yii2-google-translate-api
Google Api is a paid service however you can get free credit for 12 months if your a first time user

Load jinja2 templates dynamically on a Pyramid view

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)