Anote
Anote

Reputation: 15

django add variable to string inside a html tag

I was trying to add a variable to a string inside a html tag, but it didn't work. Here is the case, I got a variable {{comment.id}}, which is a number, 41. How could I combine {{comment.id}} with "#multiCollapseExample" in the href="..." part so it becomes href="#multiCollapseExample41"?

post_detail.html

<a class="btn btn-primary" data-toggle="collapse" href="#multiCollapseExample41" role="button" aria-expanded="false" aria-controls="multiCollapseExample41">reply</a>

Any way out? Thanks!

Upvotes: 1

Views: 1190

Answers (2)

Ian Kirkpatrick
Ian Kirkpatrick

Reputation: 1960

Make it:

<a class="btn btn-primary" data-toggle="collapse" href="#multiCollapseExample{{ comment.id }}" role="button" aria-expanded="false" aria-controls="multiCollapseExample{{ comment.id }}">reply</a>

The key here is how template tags work. They literally act as placeholders that will get replaced by a stringified version of the variable in it.

As a side note This replacement happens before the response is returned to the browser.

Upvotes: 2

Athena
Athena

Reputation: 3228

You can just include it directly; Django will fill in the template tags wherever they are, even if they're inside a HTML tag.

So in this case, all you really need to do is this:

<a class="btn btn-primary" data-toggle="collapse" href="#multiCollapseExample{{comment.id}}" role="button" aria-expanded="false" aria-controls="multiCollapseExample41">reply</a>

Upvotes: 1

Related Questions