I'm rendering HTML emails using RazorEngine and want to include helper functions. One of them uses Regex:
// template.cshtml
@using System.Text.RegularExpressions
@functions {
public string FixImageUrlParam(string url, int width, int height)
{
Regex widthParam = new Regex("w=[0-9]*");
Regex heightParam = new Regex("h=[0-9]*");
url = widthParam.Replace(url, $"w={width}");
url = heightParam.Replace(url, $"h={height}");
return url;
}
}
Here's my config/rendering logic.
// renderer.cs
public static string RenderTemplate(string template, string dataModel)
{
TemplateServiceConfiguration config = new TemplateServiceConfiguration();
config.Namespaces.Add("System.Text.RegularExpressions");
Engine.Razor = RazorEngineService.Create(config); ;
Engine.Razor.AddTemplate("template", File.ReadAllText("template.cshtml"));
Engine.Razor.Compile("template", null);
return = Engine.Razor.Run("template", null, JsonConvert.DeserializeObject<ExpandoObject>(File.ReadAllText("data.json")));
}
The problem is that my helper function causes an error when RazorEngine attempts to render. I've isolated the error to the lines that use the Regex namespace.
Errors while compiling a Template.
Please try the following to solve the situation:
* If the problem is about missing references either try to load the missing references manually (in the compiling appdomain!) or
Specify your references manually by providing your own IReferenceResolver implementation.
Currently all references have to be available as files!
* If you get 'class' does not contain a definition for 'member':
try another modelType (for example 'null' or 'typeof(DynamicObject)' to make the model dynamic).
NOTE: You CANNOT use typeof(dynamic)!
Or try to use static instead of anonymous/dynamic types.
More details about the error:
- error: (862, 35) Unexpected character '$'
\t - error: (863, 36) Unexpected character '$'
Temporary files of the compilation can be found in (please delete the folder): C:\\Users\\anstackh\\AppData\\Local\\Temp\\RazorEngine_3gknk4fd.poe
Have you tried to remove string interpolation? Most probably, this is what the error is about.
Try changing the first snippet into this:
// template.cshtml
@using System.Text.RegularExpressions
@functions {
public string FixImageUrlParam(string url, int width, int height)
{
Regex widthParam = new Regex("w=[0-9]*");
Regex heightParam = new Regex("h=[0-9]*");
url = widthParam.Replace(url, "w=" + width.ToString());
url = heightParam.Replace(url, "h=" + height.ToString());
return url;
}
}