【发布时间】:2016-07-22 09:37:23
【问题描述】:
我想用c#写一些Html(html是一个例子,这可能是其他语言..)
例如:
string div = @"<div class=""className"">
<span>Mon text</span>
</div>";
将产生:
<div class="className">
<span>Mon text</span>
</div>
从 Html 的角度来看,这不是很酷...
获得正确的 HTML 缩进的唯一方法是像这样缩进 C# 代码:
string div = @"<div class=""className"">
<span>Mon text</span>
</div>";
我们得到正确缩进的 Html:
<div class="className">
<span>Mon text</span>
</div>
但是像这样缩进 C# 确实破坏了代码的可读性...
有没有办法对 C# 语言中的缩进采取行动?
如果没有,是否有人有比以下更好的提示:
string div = "<div class=\"className\">" + Environment.NewLine +
" <span>Mon text</span>" + Environment.NewLine +
"</div>";
而且比
var sbDiv = new StringBuilder();
sbDiv.AppendLine("<div class=\"className\">");
sbDiv.AppendLine(" <span>Mon text</span>");
sbDiv.AppendLine("</div>");
我用作解决方案的方法:
非常感谢@Yotam 的回答。
我写了一个小扩展来使对齐“动态”:
/// <summary>
/// Align a multiline string from the indentation of its first line
/// </summary>
/// <remarks>The </remarks>
/// <param name="source">The string to align</param>
/// <returns></returns>
public static string AlignFromFirstLine(this string source)
{
if (String.IsNullOrEmpty(source)) {
return source;
}
if (!source.StartsWith(Environment.NewLine)) {
throw new FormatException("String must start with a NewLine character.");
}
int indentationSize = source.Skip(Environment.NewLine.Length)
.TakeWhile(Char.IsWhiteSpace)
.Count();
string indentationStr = new string(' ', indentationSize);
return source.TrimStart().Replace($"\n{indentationStr}", "\n");
}
然后我可以这样使用它:
private string GetHtml(string className)
{
return $@"
<div class=""{className}"">
<span>Texte</span>
</div>".AlignFromFirstLine();
}
返回正确的 html :
<div class="myClassName">
<span>Texte</span>
</div>
一个限制是它只适用于空格缩进...
欢迎任何改进!
【问题讨论】:
-
考虑使用对象模型构建您的 HTML,并让对象模型为您转换为字符串。
-
@EricLippert 我的示例显示了一些 Html,但我正在编写动态不同的代码格式,例如 cshtml 视图、cs 和 js 类,...我希望使用相对清晰的 C# 字符串插值语法订购我的输出代码骨架。我认为我的要求非常具体,以至于我必须为每种输出语言使用自定义模型...但是缺少时间来编写它们:-)
-
请查看(并支持)我对 Visual Studio IDE 的更改建议:Indent multi-line verbatim strings。
-
@OlivierJacot-Descombes 投票完成。很好的建议,我希望它会尽快实施...