Display global data and functions in Pyramid and Jinja 2 templates

I have a basic template when the user is logged in, and on this basic template I need to add user parameters in the drop-down menu. This drop-down menu with parameters should be constant for all handlers, i.e. Anytime a base template is invoked (extended) using a child template.

Besides executing the necessary database query, assigning the results of the query to a variable and passing this variable to each handler (there are many of them), how can I combine this into one query and one variable that is passed directly to the base template? I am using jinja2 templates.

I would really like to do something so bulky in exchange for something much simpler and more convenient.

Any ideas? Thanks.


EDIT

Therefore, I still have not found anything that I am looking for; However, I decided to at least make some progress in the interim. So, I created a custom decorator that returns a dict () view and adds the corresponding data to it. For instance:

 def get_base_data(func): def wrapper(request): d = func(request) user_id = request.user.id # used in query contact_group_data = ContactGroups.query.filter(...criteria...).all() d['contact_group_data'] = contact_group_data return d return wrapper 

Now I can at least decorate each method very briefly and simply by setting:

 @view_config(...) @get_base_data def my_handler(request): pass # rest of code... 
+6
source share
1 answer

This is one of the most unobvious things in the Pyramid and it took some time to find for me too.

You can change the global context of the template in the BeforeRender event.

http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/hooks.html#using-the-before-render-event

Alternatively, you can use class-based views, inherit all your views from the same base view class, which has get_base_data() , then the class instance is passed to the template context to all your views, and then you can retrieve data using {{ view.get_base_data }} .

http://ruslanspivak.com/2012/03/02/class-based-views-in-pyramid/

I vouch for the latter approach, as it is more beautiful, predictable and easier to maintain engineering wisdom.

+5
source

Source: https://habr.com/ru/post/956684/


All Articles