4

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 ?

2 Answers 2

7

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Works like a charm. Thank you ! Sorry for not upvoting, but I need some more reputation to do that :(
If you want to use attributes of context variables (e.g. person.name) chuck from django.template.base import resolve_variable in the top, then change the 2nd to last line to var = resolve_variable(self.varname, context).
6

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.

1 Comment

So we're even, coz I dont understand the answer :) But anyway thanks for sharing !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.