How to display a string containing django template variables?

Let's say I have a string variable called * magic_string * that is set to "This is the product name {{product.name}}" and it is available in the django template. Can I parse this variable to show me "This product name is Samsung GT-8500" (provided that the product name is "GT-8500" and the variable {{product.name}} is available using the same template)?

I tried to do something similar, but this does not work (to be honest, I'm not surprised):

{{ magic_string|safe }} 

Any ideas / suggestions about my problem?

+4
source share
2 answers

Create your own template tag and display this variable as a template. For example, see how the "ssi" tag is written.

On the other hand, can you display this line in your view? In any case, this is an unverified version of this tag:

 @register.tag def render_string(parser, token): bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError("...") return RenderStringNode(bits[1]) class RenderStringNode(Node): def __init__(self, varname): self.varname = varname def render(self, context): var = context.get(self.varname, "") return Template(var).render(context) 
+6
source

I may not understand your question, but what about,

 from django.template import Context, Template >>> t = Template("This product name is {{ product.name }}") >>> c = Context({"product.name": " Samsung GT-8500"}) >>> t.render(c) 

Sincerely.

+6
source

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


All Articles