简体   繁体   中英

Render returned string in django template

I have been working a lot with Django's template language lately, and it works well in most cases, but recently I've come across a small problem it hasn't been able to solve.
I'm iterating over a bunch of database objects, and building a button in the template from each of them. Something like this:

{% for item in items %}
    <button id="{{ item.action.id }}">
        {{ item.action.text }}
    </button>
{% endfor %}

This works fine, but my Action class is inheritable, and may have a different button structure. Say I wanted to sometimes have a javascript function attached as well. My first though was well, let's just create a render method in my class , and then call that in my template.

class ScriptAction(Action):

    def render(self):
        return '''
            <button id="{}" onclick={}>
                {}
            </button>'''.format(self.id, self.func, self.text)

Because no the template is much more elegant, and doesn't rely on a fixed button structure:

{% for item in items %}
    {{ item.action.render|safe }}
{% endfor %}

And now for my actual problem: what if this rendered string needs further processing by django?
Maybe render method returns a string like

<button id="action-button-id" onclick="console.log('clicked')">
    {{ item.name }}
</button>

Currently, {{ item.name }} will not be rendered in the template loop. Is there a way of getting around this?

Perhaps I making this more complicated than it should be, but I've looked through the Django built-in tags and filters, even looked at writing you own parser . But at this point something inside me told me that I was being obsessive. This is actually just a small problem, and would require a fair amount of time, so -

  • is this more effort than it is worth?
  • is writing complex parsers like this secure?
  • is the Django template language even able to do something like this?

If you could hone in on some of these points, I would really appreciate it. This problem is really bugging me.
Thanks in advance!

I'd look into the simple_tag option for building a custom template tag, and have the tag:

  1. Take the model instance as its argument (plus context!)
  2. Ask the model instance for a snippet of template code to use in rendering it
  3. Use the raw template API to render that template snippet
  4. Return the result, optionally marked safe if you know it is safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM