Skip to content

Commit ce9feec

Browse files
committed
Added ability to set the template filename
Adds RazorEngineCompilationOptions.TemplateFilename, which is used if not empty or whitespace. If it is it falls back to the existing Path.GetRandomFilename(). This is helpful for debugging which templates are causing errors as we can pass the error to to the user without additional information.
1 parent 96149e4 commit ce9feec

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
using Microsoft.VisualStudio.TestTools.UnitTesting;
5+
6+
namespace RazorEngineCore.Tests
7+
{
8+
[TestClass]
9+
public class TestTemplateFilename
10+
{
11+
[TestMethod]
12+
public void TestSettingTemplateFilename()
13+
{
14+
RazorEngine razorEngine = new RazorEngine();
15+
var errorThrown = false;
16+
try
17+
{
18+
IRazorEngineCompiledTemplate initialTemplate = razorEngine.Compile("@{ this is a syntaxerror }",
19+
builder => { builder.Options.TemplateFilename = "templatefilenameset.txt"; });
20+
}
21+
catch (Exception e)
22+
{
23+
Assert.IsTrue(e.Message.Contains("templatefilenameset.txt"));
24+
errorThrown = true;
25+
}
26+
27+
Assert.IsTrue(errorThrown);
28+
}
29+
}
30+
}

RazorEngineCore/RazorEngine.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ private MemoryStream CreateAndCompileToStream(string templateSource, RazorEngine
6262
builder.SetNamespace(options.TemplateNamespace);
6363
});
6464

65-
string fileName = Path.GetRandomFileName();
65+
string fileName = string.IsNullOrWhiteSpace(options.TemplateFilename) ? Path.GetRandomFileName() : options.TemplateFilename;
6666

6767
RazorSourceDocument document = RazorSourceDocument.Create(templateSource, fileName);
6868

RazorEngineCore/RazorEngineCompilationOptions.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ public class RazorEngineCompilationOptions
1212

1313
public HashSet<MetadataReference> MetadataReferences { get; set; } = new HashSet<MetadataReference>();
1414
public string TemplateNamespace { get; set; } = "TemplateNamespace";
15+
public string TemplateFilename { get; set; } = "";
1516
public string Inherits { get; set; } = "RazorEngineCore.RazorEngineTemplateBase";
1617

1718
public HashSet<string> DefaultUsings { get; set; } = new HashSet<string>()

0 commit comments

Comments
 (0)