Search code examples
pythondjangodjango-templatesargumentstemplatetags

Django .simple_tag multiple arguments


I have a simple tag that takes 2 positional arguments like this:

from django import template
from django.utils.safestring import mark_safe
@register.simple_tag
def multi(a, b):    
    html='<h1> a+b </h1>
    return mark_safe(a+b)  

And, I'm trying to use the function in my html file but I don't know how to pass the second argument, this is how I'm doing it. any ideas how can I get it? I got an error that says missing 1 required positional argument 'b':

{% load my_tags %}
{% multi 'text1' 'text2' %}

Solution

  • You were trying to concatenate your a and b arguments inside the string with no formatting logic so it was just returning <h1> a+b </h> instead of <h1>text1text2</h1>. Then you were returning mark_safe while return a+b which was ignoring your html variable, so you should be returning html inside mark_safe.

    from django import template
    from django.utils.safestring import mark_safe
    
    @register.simple_tag
    def multi(a,b): 
        html = f'<h1>{ a + b }</h1>'
        return mark_safe(html)