Nesting custom template tags

92 views
Skip to first unread message

Jon Dufresne

unread,
Mar 29, 2014, 11:24:16 AM3/29/14
to django...@googlegroups.com
Hi,

I am trying to create a custom template tag that generates a repetitive HTML snippet. This tag is an anchor tag "a" with extra classes and styles, plus some logic to apply additional classes and styles. I want the syntax in the template to look something like:

{% my_anchor URL %}this is text between opening and closing tags{% end_my_anchor %}

Where URL is set to the href attribute of the anchor tag.

The rendered result should look something like:

<a class="myclass1 myclass2" style="mystyle1; mystyle2" href="URL">this is text between opening and closing tags</a>

I also do not want to hard code my URLs. So as one might expect, I am using the "url" template tag to create correct URLs. Naively, I tried to nest the tags:

{% my_anchor {% url ... %} %}this is text between opening and closing tags{% end_my_anchor %}

But this is invalid syntax. Is there a way to handle this?

Cheers

Kelvin Wong

unread,
Apr 1, 2014, 7:38:02 PM4/1/14
to django...@googlegroups.com
You might want to look at the code for making a tag like:

URLNode(Node)

line 408 of


Then extend that.

class MyAnchor(URLNode):

override the init function to accept the params your are sending and override render so that it returns the HTML that you want.

{% my_anchor URL %}this is text between opening and closing tags{% end_my_anchor %}

would yield

<a class="myclass1 myclass2" style="mystyle1; mystyle2" href="URL">this is text between opening and closing tags</a>

K
Reply all
Reply to author
Forward
0 new messages