当我在if子句中放置一个div标记时,Razor抱怨 [英] Razor complains when I put a closing div tag in a if clause
问题描述
我正在尝试使用Razor模板进行此操作:
I am trying to do this using Razor templating:
@if(isNew)
{
<div class="new">
}
...
@if(isNew)
{
</div>
}
错误是:
cannot resolve the symbol 'div'
Razor不喜欢IF子句中的结尾div标签,如何使它起作用?我必须使用逃生吗?
Razor doesn't like the ending div tag inside the IF clause, how can I get this to work? Is there an escape I have to use?
推荐答案
当您像这样分割开始/结束标签时,Razor不喜欢它,因为它无法正确解析HTML,因此您必须将它们转义为纯文本:
Razor doesn't like it when you split start/end tags up like this as it can't parse the HTML properly, so you have to escape them as plain text:
@if(isNew)
{
@:<div class="new">
}
...
@if(isNew)
{
@:</div>
}
更传统的方法是在div内重复标记(使用局部或其他方式)-我想说,哪种方法更可取,取决于条件div之间的标记性质:
The more conventional approach would be to repeat the markup inside the div (using partials or otherwise) - which approach is more desirable, I would say, is dependent upon the nature of the markup in between the conditional divs:
@if(isNew)
{
<div class="new">
<!-- some markup or partial view -->
</div>
}
else
{
<!-- some markup or partial view -->
}
如果有以下两种情况,我会更喜欢这种方法:
I would prefer this approach if either:
- 包含的标记可以有用地包含在部分中,以便可以在其他地方重用.
- 条件包装标记不止两行,这时转义标记变得混乱.
我还应该添加使用辅助方法的选项:
I should also add the option of using helper methods:
@helper MainMarkup()
{
<!-- some markup or partial view -->
}
@if(isNew)
{
<div class="new">
@MainMarkup()
</div>
}
else
{
@MainMarkup()
}
如果您想使用上面的第二个选项,但是避免重复标记或嵌套太多的局部(特别是当该标记仅与此视图相关时),则这很有用.
This is useful if you want to use the second option above but avoid repeating markup or nesting too many partials (particularly if this markup is only relevant for this view).
这篇关于当我在if子句中放置一个div标记时,Razor抱怨的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!