【问题标题】:Can I use RazorEngine in the template.cshtml?我可以在 template.cshtml 中使用 RazorEngine 吗?
【发布时间】:2016-06-23 08:37:39
【问题描述】:
这里我有一个资源文件,里面有文本字符串,像这样:
尊敬的@Model.SupporterName,来自公司的@Model.ConsumerName
@Model.ConsumerCompany 为团队开放访问下一个许可协议
工作
在我的 View.cshtml 中,我使用资源中的字符串
<tr>
<td class="free-text">
@Resources.ActivatedBodyText
</td>
</tr>
并使用指定的模型运行编译。
但是!
全部渲染后,html文件如下所示:
Click
如何使用 RazorEngine 从资源中渲染字符串????
【问题讨论】:
标签:
razor
resources
razorengine
【解决方案1】:
以下内容对我有用:
结果:
控制器动作:
public ActionResult Index()
{
string templateStr = Resources.ActivatedBodyText;
Template product = new Template() { SupporterName = "Support1", ConsumerCompany = "Company1", ConsumerName = "Consumer1" };
string pattern = @"\@Model\.(\w+)";
Regex rgx = new Regex(pattern);
MatchCollection matches = rgx.Matches(templateStr);
foreach (Match match in matches)
{
string capture = match.Groups[1].Value;
string propertyvalue = product.GetType().GetProperty(capture).GetValue(product).ToString();
templateStr = templateStr.Replace(match.ToString(), propertyvalue);
}
ViewBag.templateStr = templateStr;
return View();
}
说明:
- 找到“@Model”的所有实例。在资源字符串中并使用正则表达式捕获属性名称
- 循环遍历每个匹配项并通过反射获得属性值
- 将匹配的“@Model...”表达式替换为属性值
- 通过 ViewBag 将新模板字符串传递给视图