简体   繁体   中英

Getting HTML headings to be dynamically output by Razor

I am creating a page in Razor and I am trying to dynamically output headings depending on how deep the node is.

So the top level node is a h1, second level h2 etc...

The bit I am struggling is getting razor to dynamically output the headings. Half of it seems to be working but the closing tag will not output.

This is the razor:

<h@{@parts} id="#@item.Id">@sectionString@level @item.Name </h@{@parts} >

Which outputs the following HTML:

<h4 id="#1073">4.1.1 Get a baseline </h@{@parts} >

If I remove the forward slash it works, but then i end up with <h3><h3> rather than <h3></h3> .

I have also tried:

<h@{@parts} id="#@item.Id">@sectionString@level @item.Name </h@parts >

<h@{@parts} id="#@item.Id">@sectionString@level @item.Name </h@{parts} >

If I can't get this to work I guess I will have to resort to a very long if statement which I would rather avoid. I think the slash needs escaping somehow? Thank-you.

Worked it out!

<h@{@parts} id="#@item.Id">@sectionString@level @item.Name @Html.Raw("</h")@parts@Html.Raw(">")

I just had to escape the code, it doesn't look tidy but it works.

Edit: The comments below show a much better way of doing this. Thanks for those!

Better to make a helper:

@Heading(1, (sectionString + level + item.Name), item.Id)
@Heading(2, "Sub heading")
@Heading(3, "Lesser heading", "anyId")

@helper Heading(int headingLevel, string title, string id = null)
{
    @if (id != null)
    {
        @Html.Raw(string.Format(@"<h{0} id=""{1}""",  headingLevel, Html.Encode(id)))
    }
    else
    {
        @Html.Raw(string.Format("<h{0}>",  headingLevel))
    }
    @title
    @Html.Raw(string.Format("</h{0}>", headingLevel))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM