Matthew Dresser
Matthew Dresser

Reputation: 11442

Build html tag using variable name for element

I want to use a string variable which could contain the values h1, h2, h3 etc to build some html. This works fine for the opening tag, but does not work nicely for the closing tag. If I write

@{ var tag = "h1" ; }
<@tag>some title here</@tag>

I end up with the html

<h1>some title here</@h1>

A work-around which seems to work is

<@tag>some title here<@("/"+tag)>

but it's pretty ugly. Is there some escape sequence I need to use here?

Upvotes: 2

Views: 1774

Answers (3)

Mikael Tetenkin
Mikael Tetenkin

Reputation: 1

@Html.Raw($"<{tag}>some title here</{tag}>")

Upvotes: 0

Fatih
Fatih

Reputation: 1145

You can use Html.Raw.

string lineTemplate = "<h{0}>{1}</h{0}>";
for (int tagCounter = 1; tagCounter < 7; tagCounter++)
{
    @Html.Raw(string.Format(lineTemplate, tagCounter, "Header "+ tagCounter));
}

Upvotes: 1

Ray H
Ray H

Reputation: 521

i am not sure which Razor version you are using

but i tested your code in my MVC4, it works perfectly

it will render <h1>something</h1>

Upvotes: 0

Related Questions