I ended up using XSLT in the end, as it is robust, secure and building an XML document to parse is far simpler and more flexible than previous approaches.
Templating languages and how to restrict access to Namespaces in Razor template
-
29-09-2022 - |
Pergunta
Background
I have a web service that returns entity objects with a dynamic list of fields. Currently the web service can return the entities, but I want to make it simpler, and allow the client to provide a template string that I parse using the entity and then return the result.
Here is an example:
var entity = new Entity();
entity.Fields.Add("status", "worked");
var template = "My template parser {{status}}!";
var result = service.ParseTemplate(template, entity);
// Expected result is "My template parser worked!"
This much I can do using a simple regex. I then decided I needed some basic logic, such as for loops and if statements. I decided to use Cottle, which is a great open source templating engine. Unfortunately this isn't going to cut it as my entity grows more complex. Here is the kind of thing I want to do:
var entity = new Entity();
entity.Fields.Add("name", "Bob");
var entity2 = new Entity();
entity2.Fields.Add("status", "worked");
entity2.Fields.Add("person", entity);
var template = "My name is {{person.name}}. My template parser {{status}}!";
var result = service.ParseTemplate(template, entity2);
// Expected result is "My name is Bob. My template parser worked!"
As you can see, this second example allows a dot based syntax to find the attached entity and read its fields as well.
Now onto the meat of the question...
I decided that Razor can accomplish what I am looking for using the RazorEngine project. However I am hesitant to invite people to send me a template filled with server side code for obvious reasons. Is there a way that I can parse the template while removing access to the entire .Net library?
Alternative question
Is there a better templating solution out there that anyone can recommend?
Solução