0

In a template I created for my Django view I pass an extra variable called Item. This Item object has a string representation of the value it holds. It kinda looks like this:

class Item:
    value = ''
    previous_item = Item

    def __str__(self):
        return '%s > %s' % (value, previous_item)

This way you can get a chain of items: value_x > value_y > value_z

The problem is that now I want to be able to just print the vars of the Item object I injected into the template, much like the vars() function in Python:

>>> item = Item('FooBar', None)
>>> vars(item)

In my template I want to do the same:

<div>
    {{ item }}. {# prints `value_x > value_y > value_z` #}
    {{ vars item }}  {# should print <Item: value_x, None>  or something like that #}
</div>

Is there a way to do pythons vars() in the template?

Workaround

So for now I'm using an awful slow approach. To get the vars of the template variable i'm adding the vars to the context myself before rendering the template like this:

    ctx = super(MyView, self).get_context(*args, **kwargs)
    ctx['vars'] = vars(self)
    ctx['item_vars'] = vars(self.item)
    return ctx
Nebulosar
  • 1,727
  • 3
  • 20
  • 46
  • 1
    https://stackoverflow.com/a/1333277/7636315 It discusses how a custom template filter can be used to accomplish that. Is this what u require? – Paandittya Apr 03 '18 at 10:50
  • Well, this is not what I want, but it brought me where I want to go. A temporary registered tag is a way to go I guess. Thanks for the reference! – Nebulosar Apr 03 '18 at 11:02

1 Answers1

0

I made a simple solution with the help of Paandittya that pointed out another question, what somewhat looks like what I need in this situation:

@register.simple_tag
    def var(value)
        return vars(value)

Then in the template, load in the tag and call it:

{% load my_tags %}
{% var item %}
Nebulosar
  • 1,727
  • 3
  • 20
  • 46