简体   繁体   English

让Razor动态输出HTML标题

[英]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. 我正在Razor中创建一个页面,并且尝试根据节点的深度来动态输出标题。

So the top level node is a h1, second level h2 etc... 所以顶层节点是h1,二级节点h2等...

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: 输出以下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> . 如果我删除正斜杠,则可以使用,但最终以<h3><h3>而不是<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. 如果我无法解决这个问题,我想我将不得不求助于很长的if语句,而我宁愿避免。 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))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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