Search code examples
djangodjango-templatesdjango-template-filters

how to use value for loop in text content in django


I have textfield value that is populated in by the user. I want to create my own "tag" of sorts so that when present, I can loop through its return value.

Here is example of content that my be entered by the user:

my awesome content starts

(-- assets --)

ending portion of my content

I'm thinking a template tag would be used for this do something along the lines of:

{{ mycontent|check_if_assets_present }}

Then this would print something like:

my awesome content starts

  1. Asset 1
  2. Asset 2
  3. Asset 3

ending portion of my content

How can I accomplish this in a django template?


Solution

  • I ended up creating a template tag and then replacing when the character set is encountered:

    from django import template
    
    register = template.Library()
    
    
    @register.filter(name='add_assets')
    def add_assets(composition):
        if '(-- assets --)' in composition.content:
    
            asset_group = AssetGroup.objects.filter(composition=composition)
            unordered_list_str = asset_group_to_html(asset_group)
            composition.content = composition.content.replace('(-- assets --)', unordered_list_str)
    
        return composition.content