Reputation: 2611
I am using RazorEngine to render out some basic content (a very crude content management system).
It works great until I include any @Html syntax into markup.
If the markup contains an @html I get the following error:
Unable to compile template. The name 'Html' does not exist in the current context
This is the view that renders the markup:
@Model Models.ContentPage
@{
ViewBag.Title = Model.MetaTitle;
Layout = "~/Views/Shared/Templates/_" + Model.Layout + "Layout.cshtml";
}
@Html.Raw(RazorEngine.Razor.Parse(Model.Markup, Model))
I have seen on the Codeplex site for RazorEngine the use of @Html (I know the version on there is out of date and I got my version via nuget).
Any help on this would be great.
Upvotes: 35
Views: 30806
Reputation: 848
Modification of mao47's answer for latest razor syntax, this will also support partial views, and many other helper methods since it's getting Microsoft's helpers out of System.Web.Mvc.dll instead of just recreating some of their methods.
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Web.Hosting;
using System.Xml.Linq;
using RazorEngine.Configuration;
using RazorEngine.Templating;
public static class DynamicRazorTemplateParser
{
private static readonly IRazorEngineService service = RazorEngineService.Create(TemplateServiceConfiguration);
public static string RunCompile<T>(string template, string placeholder, T model, DynamicViewBag viewBag) where T : class
{
var templateSource = new LoadedTemplateSource(template);
return RunCompile(templateSource, placeholder, model, viewBag);
}
public static string RunCompile<T>(ITemplateSource template, string placeholder, T model, DynamicViewBag viewBag) where T : class
{
return service.RunCompile(template, placeholder, model.GetType(), model, viewBag);
}
public static string RunCompile(ITemplateSource template, string placeholder)
{
return service.RunCompile(template, placeholder);
}
private static TemplateServiceConfiguration TemplateServiceConfiguration
{
get
{
var config = new TemplateServiceConfiguration
{
BaseTemplateType = typeof(HtmlTemplateBase<>),
TemplateManager = new TemplateManager()
};
//TODO: Is this the best way?
var xDocument = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "/Views/Web.config");
if (xDocument.Root != null)
{
var sysWeb = xDocument.Root.Element("system.web.webPages.razor");
if (sysWeb == null) return config;
var pages = sysWeb.Element("pages");
if (pages != null)
{
var namespaces = pages.Element("namespaces");
if (namespaces != null)
{
var namespacesAdd = namespaces.Elements("add")
.Where(x => x.Attribute("namespace") != null)
.Select(x =>
x.Attribute("namespace").Value
);
foreach (var ns in namespacesAdd)
{
config.Namespaces.Add(ns);
}
}
}
}
return config;
}
}
private class TemplateManager : ITemplateManager
{
private readonly ConcurrentDictionary<ITemplateKey, ITemplateSource> _dynamicTemplates = new ConcurrentDictionary<ITemplateKey, ITemplateSource>();
private readonly string baseTemplatePath;
public TemplateManager()
{
baseTemplatePath = HostingEnvironment.MapPath("~/Views/");
}
public ITemplateSource Resolve(ITemplateKey key)
{
ITemplateSource templateSource;
if (this._dynamicTemplates.TryGetValue(key, out templateSource))
return templateSource;
string template = key.Name;
var ubuilder = new UriBuilder();
ubuilder.Path = template;
var newURL = ubuilder.Uri.LocalPath.TrimStart('/');
string path = Path.Combine(baseTemplatePath, string.Format("{0}", newURL));
string content = File.ReadAllText(path);
return new LoadedTemplateSource(content, path);
}
public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context)
{
return new NameOnlyTemplateKey(name, resolveType, context);
}
public void AddDynamic(ITemplateKey key, ITemplateSource source)
{
this._dynamicTemplates.AddOrUpdate(key, source, (k, oldSource) =>
{
if (oldSource.Template != source.Template)
throw new InvalidOperationException("The same key was already used for another template!");
return source;
});
}
}
}
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using RazorEngine.Templating;
using RazorEngine.Text;
// ReSharper disable ClassWithVirtualMembersNeverInherited.Global
// ReSharper disable MemberCanBePrivate.Global
namespace Common.Core.Razor
{
[RequireNamespaces("System.Web.Mvc.Html")]
public class HtmlTemplateBase<T> : RazorEngine.Templating.HtmlTemplateBase<T>, IViewDataContainer
{
private HtmlHelper<T> helper;
private ViewDataDictionary viewdata;
private TempDataDictionary tempdata;
private AjaxHelper<T> ajaxHelper;
private ViewContext viewContext;
private UrlHelper urlHelper;
private readonly RequestContext _requestContext = HttpContext.Current.Request.RequestContext;
public UrlHelper Url => urlHelper ?? (urlHelper = new UrlHelper(_requestContext));
public ViewContext ViewContext
{
get
{
if (viewContext != null) return viewContext;
viewContext = GetViewContext();
return viewContext;
}
}
public AjaxHelper<T> Ajax
{
get
{
if (ajaxHelper != null) return ajaxHelper;
ajaxHelper = new AjaxHelper<T>(ViewContext, this);
return ajaxHelper;
}
}
public HtmlHelper<T> Html
{
get
{
if (helper != null) return helper;
helper = new HtmlHelper<T>(ViewContext, this);
return helper;
}
}
public ViewDataDictionary ViewData
{
get
{
if (viewdata == null)
{
viewdata = new ViewDataDictionary
{
TemplateInfo = new TemplateInfo() { HtmlFieldPrefix = string.Empty }
};
if (Model != null)
{
viewdata.Model = Model;
}
}
return viewdata;
}
set
{
viewdata = value;
}
}
public TempDataDictionary TempData
{
get { return tempdata ?? (tempdata = new TempDataDictionary()); }
set
{
tempdata = value;
}
}
public virtual string RenderView()
{
using (var writer = new StringWriter())
{
ViewContext.View.Render(ViewContext, CurrentWriter);
return writer.GetStringBuilder().ToString();
}
}
private ViewContext GetViewContext()
{
if (HttpContext.Current == null) throw new NotImplementedException();
var requestContext = _requestContext;
var controllerContext = ControllerContext(requestContext);
var view = GetView(requestContext, controllerContext);
//Can't check if string writer is closed, need to catch exception
try
{
var vContext = new ViewContext(controllerContext, view, ViewData, TempData, CurrentWriter);
return vContext;
}
catch
{
using (var sw = new StringWriter())
{
var vContext = new ViewContext(controllerContext, view, ViewData, TempData, sw);
return vContext;
}
}
}
private IView GetView(RequestContext requestContext, ControllerContext controllerContext)
{
if ((string)requestContext.RouteData.DataTokens["Action"] != null)
{
requestContext.RouteData.Values["action"] = (string)requestContext.RouteData.DataTokens["Action"];
}
var action = requestContext.RouteData.GetRequiredString("action");
var viewEngineResult = ViewEngines.Engines.FindPartialView(controllerContext, action);
if (viewEngineResult != null && viewEngineResult.View != null)
{
return viewEngineResult.View;
}
viewEngineResult = ViewEngines.Engines.FindView(controllerContext, action, null);
if (viewEngineResult == null)
{
throw new Exception("No PartialView assigned in route");
}
return viewEngineResult.View;
}
public void SetView(string view)
{
_requestContext.RouteData.DataTokens["Action"] = view;
}
private ControllerContext ControllerContext(RequestContext requestContext)
{
ControllerBase controllerBase;
var routeDataValue = "EmptyController";
if (requestContext.RouteData.Values["controller"] != null && (string)requestContext.RouteData.Values["controller"] != routeDataValue)
{
var controllerName = (string)requestContext.RouteData.Values["controller"];
IController controller = ControllerBuilder.Current.GetControllerFactory().CreateController(requestContext, controllerName);
controllerBase = controller as ControllerBase;
}
else
{
var controller = new EmptyController();
controllerBase = controller; //ControllerBase implements IController which this returns
requestContext.RouteData.Values["controller"] = routeDataValue;
}
var controllerContext =
new ControllerContext(requestContext.HttpContext, requestContext.RouteData, controllerBase);
return controllerContext;
}
private class EmptyController : Controller { }
public override void WriteTo(TextWriter writer, object value)
{
if (writer == null)
throw new ArgumentNullException("writer");
if (value == null) return;
//try to cast to RazorEngine IEncodedString
var encodedString = value as IEncodedString;
if (encodedString != null)
{
writer.Write(encodedString);
}
else
{
//try to cast to IHtmlString (Could be returned by Mvc Html helper methods)
var htmlString = value as IHtmlString;
if (htmlString != null) writer.Write(htmlString.ToHtmlString());
else
{
//default implementation is to convert to RazorEngine encoded string
base.WriteTo(writer, value);
}
}
}
}
}
Upvotes: 1
Reputation: 1155
My answer uses the answer by hannes neukermans.
I needed to use RazorEngine to send emails incorporating html strings stored in a database so that they could be edited by admin users.
The standard config didn't allow @Html.Raw to work.
In my emails class I set up a new Engine.Razor (Engine is static) that incorporates the classes Hannes recommends. I only needed the Raw method, but you can obviously add others :
public class HtmlSupportTemplateBase<T> : TemplateBase<T>
{
public HtmlSupportTemplateBase()
{
Html = new MyHtmlHelper();
}
public MyHtmlHelper Html { get; set; }
}
public class MyHtmlHelper
{
/// <summary>
/// Instructs razor to render a string without applying html encoding.
/// </summary>
/// <param name="htmlString"></param>
/// <returns></returns>
public IEncodedString Raw(string htmlString)
{
return new RawString(WebUtility.HtmlEncode(htmlString));
}
}
I could then use @Html.Raw in my emails template to incorporate the editable html
public class Emails
{
public static TemplateServiceConfiguration config
= new TemplateServiceConfiguration(); // create a new config
public Emails()
{
config.BaseTemplateType = typeof(HtmlSupportTemplateBase<>);// incorporate the Html helper class
Engine.Razor = RazorEngineService.Create(config);// use that config to assign a new razor service
}
public static void SendHtmlEmail(string template, EmailModel model)
{
string emailBody
= Engine.Razor.RunCompile(template, model.Type.ToString(), typeof(EmailModel), model);
the following is not really part of the answer but gives useful code to those who are using it for emails :)
var smtpClient = getStaticSmtpObject(); // an external method not included here
MailMessage message = new MailMessage();
message.From = new MailAddress(model.FromAddress);
message.To.Add(model.EmailAddress);
message.Subject = model.Subject;
message.IsBodyHtml = true;
message.Body = System.Net.WebUtility.HtmlDecode(emailBody);
smtpClient.SendAsync(message, model);
}
}
Then I could use it by passing in the string read from the actual .cshtml template and the model holding the email data. (ResolveConfigurationPath is another external function I found in this page)
string template = System.IO.File.ReadAllText(ResolveConfigurationPath("~/Views/Emails/MAPEmail.cshtml"));
SendHtmlEmail(template, model);
Upvotes: 3
Reputation: 13257
Html.Raw Simplest solution !! 3 steps needed
Step 1: Inherit from TemplateBase:
public class HtmlSupportTemplateBase<T> : TemplateBase<T>
{
public HtmlSupportTemplateBase()
{
Html = new MyHtmlHelper();
}
public MyHtmlHelper Html { get; set; }
}
Step 2: Create a object that makes available all Html methods consumed by your template. In this example Html.Raw and Html.Encode become available in the cshtml. template
public class MyHtmlHelper
{
/// <summary>
/// Instructs razor to render a string without applying html encoding.
/// </summary>
/// <param name="htmlString"></param>
/// <returns></returns>
public IEncodedString Raw(string htmlString)
{
return new RawString(htmlString);
}
public string Encode(string value)
{
return System.Net.WebUtility.HtmlEncode(value);
}
public string Encode(object value)
{
return "do whatever";
}
}
Step 3:
var config = new TemplateServiceConfiguration
{
TemplateManager = templateManager,
BaseTemplateType = typeof(HtmlSupportTemplateBase<>)
};
Upvotes: 3
Reputation: 779
It's quite old question but I found good answer on coderwall. The solution is to use:
@(new RawString("<strong>Bold!</strong>"))
or just:
@(new RawString(Model.YourHTMLStrinInModel))
I hope it's helpfull.
Upvotes: 13
Reputation: 967
This is over a year old, but since I haven't found a working copy anywhere on the internet and the github page is inactive, I figured I would share my implementation to add @Html helper syntax to RazorEngine. Here is the implementation I ended up with, using Abu Haider's implementation as a starting point.
Courtesy of miketrash's comment: If you are trying to use @Html.Action(), you will need to add the RequestContext (you can use HttpContext.Current.Request.RequestContext
). I did not include request context because it is not always available for my application.
[RequireNamespaces("System.Web.Mvc.Html")]
public class HtmlTemplateBase<T>:TemplateBase<T>, IViewDataContainer
{
private HtmlHelper<T> helper = null;
private ViewDataDictionary viewdata = null;
public HtmlHelper<T> Html
{
get
{
if (helper == null)
{
var writer = this.CurrentWriter; //TemplateBase.CurrentWriter
var vcontext = new ViewContext() { Writer = writer, ViewData = this.ViewData};
helper = new HtmlHelper<T>(vcontext, this);
}
return helper;
}
}
public ViewDataDictionary ViewData
{
get
{
if (viewdata == null)
{
viewdata = new ViewDataDictionary();
viewdata.TemplateInfo = new TemplateInfo() { HtmlFieldPrefix = string.Empty };
if (this.Model != null)
{
viewdata.Model = Model;
}
}
return viewdata;
}
set
{
viewdata = value;
}
}
public override void WriteTo(TextWriter writer, object value)
{
if (writer == null)
throw new ArgumentNullException("writer");
if (value == null) return;
//try to cast to RazorEngine IEncodedString
var encodedString = value as IEncodedString;
if (encodedString != null)
{
writer.Write(encodedString);
}
else
{
//try to cast to IHtmlString (Could be returned by Mvc Html helper methods)
var htmlString = value as IHtmlString;
if (htmlString != null) writer.Write(htmlString.ToHtmlString());
else
{
//default implementation is to convert to RazorEngine encoded string
encodedString = TemplateService.EncodedStringFactory.CreateEncodedString(value);
writer.Write(encodedString);
}
}
}
}
I also had to override the WriteTo
method of TemplateBase
, because otherwise RazorEngine will html-encode the result of the helper method meaning you'll escape the '<', '>', and quotes (see this question). The override adds a check for the value being an IHtmlString
before resorting to performing an encoding.
Upvotes: 13
Reputation: 3164
My apologies, I do not have the required 50 reputation to add a comment so have to put an answer.
If anybody is wondering (as JamesStuddart was) the SetTemplateBase() method is missing but you can create a configuration instance to initialise a service with your base template.
From http://razorengine.codeplex.com/discussions/285937 I adapted my code so it looks like:
var config = new RazorEngine.Configuration.TemplateServiceConfiguration
{
BaseTemplateType = typeof(MyHtmlTemplateBase<>)
};
using (var service = new RazorEngine.Templating.TemplateService(config))
{
// Use template service.
Razor.SetTemplateService(service);
result = Razor.Parse(templateString, model);
}
Upvotes: 5
Reputation: 1712
Check https://github.com/Antaris/RazorEngine/wiki/6.-Encoding-Values page. I copy / past it here:
By default, RazorEngine is configured to encode as HTML. This sometimes presents problems where certain characters are encoded as HTML when you wanted the output to be as-is.
To output something in raw format, use the @Raw() built-in method as shown in the following example:
string template = "@Raw(Model.Data)";
var model = new { Data = "My raw double quotes appears here \"hello!\"" };
string result = Razor.Parse(template, model);
Which should result in:
My raw double quotes appears here "hello!"
Upvotes: 31
Reputation: 61589
The Html
and Url
helper properties are actual features of MVC's implementation of Razor in their view engine. Out of the box, Html
and Url
are not currently supported without specialising a custom base template.
The upcoming v3 release will be accompanied by an associated RazorEngine.Web release, which will hopefully include an MVC3 compatible base template with Html
and Url
support.
The example I wrote on the project homepage, is purely an example of using a custom base template.
You can find out more about v3 at https://github.com/Antaris/RazorEngine
Upvotes: 19