我有一些html,我想用另一个标签包装。
例如,这将是一个未读的文件:
var Controller = require('./controller');
var Event = function() {
this.element = 'element';
Controller.call(this);
};
// See here!
Event.prototype = Object.create(Controller.prototype);
// Note other Event.prototype additions must be *after* the above line.
Event.prototype.another = function () {
console.log('Another');
this.method();
};
var event = new Event();
这将是一份阅读文件:
<strong>
<a href="viewDocument">
View Document
</a>
</strong>
除了添加两个<a href="viewDocument">
View Document
</a>
语句之外,还有更简单的方法吗?这种方式有点笨重
@if
答案 0 :(得分:1)
基于this answer我改编了一个可选的包装HtmlHelper,我认为它对其他人有用。仅当提供的@if(test)
{
@:<strong>
}
<a href="viewDocument">
View Document
</a>
@if(test)
{
@:</strong>
}
计算结果为true时,才会包装html。
在Html Helpers的静态类中:
test
班级:
public static IDisposable BeginOptionalWrap(this HtmlHelper helper, string tag, bool test, object htmlAttributes = null)
{
var tb = new TagBuilder(tag);
var attrs = GetAttributes(htmlAttributes);
if (attrs != null)
{
tb.MergeAttributes(attrs);
}
if (test)
{
helper.ViewContext.Writer.Write(tb.ToString(TagRenderMode.StartTag));
}
return new OptionalWrap(helper, tb, test);
}
用法:
public class OptionalWrap : IDisposable
{
private readonly HtmlHelper _Helper;
private readonly TagBuilder _Tag;
private readonly bool _test;
public OptionalWrap(HtmlHelper helper, TagBuilder tag, bool test)
{
_Helper = helper;
_Tag = tag;
_test = test;
}
public void Dispose()
{
if (_test)
{
_Helper.ViewContext.Writer.Write(_Tag.ToString(TagRenderMode.EndTag));
}
}
}