1

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!

2
  • what if "#multiCollapseExample{{comment.id}}" ? Commented Aug 28, 2018 at 17:08
  • @BearBrown, yeah, it works, thanks! Commented Aug 29, 2018 at 3:21

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.