Ryan
Ryan

Reputation: 61

string_if_invalid django or ninja template: custom renderer in selected html string

i'm looking for a solution to selectively not replace missing variables/replace by whatever in django:

I have a text, defined by a user, where he can insert variables {{model.myvar}}. In the backend, i render the text and the context to return a text which can be then modified if necessary.

So far so good...

For UX reasons, the variables can be entered at different times, and the text be generated at any time...So if all the var are not entered, there will be empty strings...

What i'm looking for is a way to get the free text with variables, and "generate" it as often as wanted ! So the text is sent to the backend, if the corresponding var is in the context => var is replaced ! but if there is not: return {{myvar}}. Then the txt can be re-generated later with appropriate information !

I deeply searched for a solution with django template and jinja. Indeed i explored "string_if_invalid" for django: but apply in all the app and can create problems. I'm looking for a custom solution which i can apply selectively in selected parts of my codes...

-Is it possible ? -How...?!

Thanks for your help !

EDIT:

well, let's say you have a raw text:

text = blablabla {{model.var1}} blabalbal {{model.var2}} etc... This text is sent to the backend:

# generate text type with variables feeded !
# 1/ generate variables of the template (script !)
context = myobject # can be incomplete...That's the trick

# 2/ generate a "template" from the text
template = Template(text)

# 3/ generate text filled with variables
c = Context(context)  
final_text = template.render(c)

return HttpResponse(final_text)

The point is considering that the object can be updated later, but the text "generated" now, then modified according to the user wishes, i'd like the {{model.var1}} to return {{model.myvar1}} if myvar1 does not exists yet ! Then the text can be re-send to the "generator" and empty variables can be rendered !

Another trick is i need this specific features only in some part of the project...

Ninja is an alternative at django template engine, but i'm not familiar with it. Just wondering if it is possible with it or more customizable than django templates engine.

Hope it is clear enough !

Thanks for your help !

Upvotes: 0

Views: 46

Answers (0)

Related Questions