Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display string which contains django template variables?

Let's say I have an string variable called *magic_string* which value is set to "This product name is {{ product.name }}" and it's avaible at django template. Is it ever possible to parse that variable to show me "This product name is Samsung GT-8500" instead (assuming that name of the product is "GT-8500" and variable {{ product.name }} is avaible at the same template) ?

I was trying to do something like this, but it doesn't work (honestly ? Im not surprised):

{{ magic_string|safe }}

Any ideas/suggestions about my problem ?

like image 862
Kamil Rykowski Avatar asked Dec 12 '22 07:12

Kamil Rykowski


2 Answers

Write custom template tag and render that variable as a template. For example look at how "ssi" tag is written.

On the other hand, can you render this string in your view? Anyway here is an untested version of that 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)
like image 178
alex vasi Avatar answered Apr 28 '23 04:04

alex vasi


Perhaps I dont 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)

Regards.

like image 41
pvilas Avatar answered Apr 28 '23 02:04

pvilas