Search code examples
djangopug

What is the proper syntax for using a django template variable as a jade href id reference?


I am trying to generate a navigation table using a django template for loop. The href target includes a django variable. The django template is written in jade format.

If i were using HTML format in the django template, I would use:

<a href="#{{group.name}}"> {{group.name}} </a>

But I can't find the correct syntax using jade format.

What I have is:

table.generic
  tbody
    tr
      th Jump to a Group
    {% for group in groups %}
    tr
      td
        a(href!='#{{group.name}}') {{group.name}}
    {% endfor %}

But the anchors are rendered in HTML as:

<a +{group.name.__str__()+'}'="" href="">Registration</a>

"Registration" is a value for group.name.

Removing the ! causes a django render error.

I tried to insert a backslash: a(href!='#\{{group.name}}') {{group.name}}, but this renders with the backslash intact as:

<a href="#\Registration">Registration</a>

Suggestions?

Edit: As a terrible work-around, I have added a "pound" method to return the group name with a # prefix:

def pound(self): 
    return unicode("#" + self.name)

Now I can reference {{group.pound}} in the jade template:

a(href!='{{group.pound}}') {{group.name}}

Maybe a better method name would be group.name_as_id_tag ....


RESOLVED: Format the django template variable as a jade variable

Based on the last suggestion from @user1737909, I extended the suggestion to try:

a(href='##{group.name}') {{group.name}}

The key is to format the double-curly django variable {{}} as pound-single-curly jade variable #{}. Do not include the ! before the = sign so the variable is evaluated by jade which will insert the value it gets from django.

I wish I could find a link to a coding style reference page to include here. But if I had one, I would not have asked this question in the first place.


Solution

  • Based on the last suggestion from @user1737909, I extended the suggestion to try:

    a(href='##{group.name}') {{group.name}}
    

    The key is to format the double-curly django variable {{}} as pound-single-curly jade variable #{}. Do not include the ! before the = sign so the variable is evaluated by jade which will insert the value it gets from django.

    OP updated to reflect this solution.