jinja2: How to make it fail Silently like djangotemplate

2024/9/8 10:29:29

Well i don't find the answer I'm sure that it's very simple, but i just don't find out how to make it work like Django when it doesn't find a variable

i tried to use Undefined and create my own undefined but it give me problems of attribute error etc.

def silently(*args, **kwargs):return u''class UndefinedSilently(Undefined):__unicode__ = silently__str__ = silently__call__ = silently__getattr__ = silently

but when i try this here it fails TypeError: 'unicode' object is not callable:

{%for dir_name, links in menu_links.items()%}
Answer

You are trying to go arbitrarily deep into your undefined data. menu_links is undefined, so Jinja2 creates a new instance of your UndefinedSilently class. It then calls the __getattr__ method of this object to get the items attribute. This returns a blank unicode string. Which Python then tries to call (the () of menu_links.items()). Which raises the error that unicode objects are not callables.

That is:

menu_links.items() # becomes
UndefinedSilently().items() # becomes
UndefinedSilently().u''() # from UndefinedSilently.__getattr__

If you want to be able to go deeper than one level you can create a class that returns itself for every access attempt except __str__ and __unicode__.

def silently(*args, **kwargs):return u''return_new = lambda *args, **kwargs: UndefinedSilently()class UndefinedSilently(Undefined):__unicode__ = silently__str__ = silently__call__ = return_new__getattr__ = return_new
https://en.xdnf.cn/q/72730.html

Related Q&A

ImportError when from transformers import BertTokenizer

My code is: import torch from transformers import BertTokenizer from IPython.display import clear_outputI got error in line from transformers import BertTokenizer: ImportError: /lib/x86_64-linux-gnu/li…

How to get feature names of shap_values from TreeExplainer?

I am doing a shap tutorial, and attempting to get the shap values for each person in a dataset from sklearn.model_selection import train_test_split import xgboost import shap import numpy as np import …

How can I clear a line in console after using \r and printing some text?

For my current project, there are some pieces of code that are slow and which I cant make faster. To get some feedback how much was done / has to be done, Ive created a progress snippet which you can s…

installing pyaudio to docker container

I am trying to install pyaudio to my docker container and I was wondering if anyone had any solution for Windows. I have tried two methods: Method 1: Using pipwin - Error Code: => [3/7] RUN pip inst…

Escaping special characters in elasticsearch

I am using the elasticsearch python client to make some queries to the elasticsearch instance that we are hosting.I noticed that some characters need to be escaped. Specifically, these...+ - &&…

Interacting with live matplotlib plot

Im trying to create a live plot which updates as more data is available.import os,sys import matplotlib.pyplot as pltimport time import randomdef live_plot():fig = plt.figure()ax = fig.add_subplot(111)…

pandas groupby: can I select an agg function by one level of a column MultiIndex?

I have a pandas DataFrame with a MultiIndex of columns:columns=pd.MultiIndex.from_tuples([(c, i) for c in [a, b] for i in range(3)]) df = pd.DataFrame(np.random.randn(4, 6),index=[0, 0, 1, 1],columns=c…

Bottle web app not serving static css files

My bottle web application is not serving my main.css file despite the fact I am using the static_file method.app.pyfrom bottle import * from xml.dom import minidom @route(/) def index():return template…

How to wrap text in OpenCV when I print it on an image and it exceeds the frame of the image?

I have a 1:1 ratio image and I want to make sure that if the text exceeds the frame of the image, it gets wrapped to the next line. How would I do it?I am thinking of doing an if-else block, where &qu…

pandas series filtering between values

If s is a pandas.Series, I know I can do this:b = s < 4or b = s > 0but I cant dob = 0 < s < 4orb = (0 < s) and (s < 4)What is the idiomatic pandas method for creating a boolean series…