0

I'm trying to get Scriban to ignore errors when parsing a template, so it will partially format.

For instance

var template = Template.Parse("{{foo}} {{bar.}}");
template.Parse(new { foo = 1 });

This throws an InvalidOperationException. What I want to get is something like

1 {{bar.}}

or

1 ERROR

Is there any way to do that?

Currently, I'm doing this:

try
{
    var template = Template.Parse(input);
    return template.Render(variables);
}
catch (Scriban.Syntax.ScriptRuntimeException ex)
{
    return input;
}
catch (InvalidOperationException ex)
{
    return input;
}

But that gives me the whole string without any replacements if there is an error.

I want to handle this in my code, rather than customizing the template, because we're effectively using Scriban "backwards". Our users will be writing simple templates to be filled in with predefined values.

RoadieRich
  • 6,330
  • 3
  • 35
  • 52

1 Answers1

-1

The issue is that your template doesn't tell the code how to handle a null input.

From https://zetcode.com/csharp/scriban/

Scriban conditions We can use if/else if/else conditions in templates.

Program.cs
using Scriban;

string?[] names = { "John", "Nelly", null, "George" };

var data = @"
{{- for name in names -}}
  {{ if !name  }}
Hello there!
  {{ else }}
Hello {{name}}!
  {{ end }}
{{- end }}";

var tpl = Template.Parse(data);
var res = tpl.Render(new { names = names });

Console.WriteLine(res);

We have an array of names. With the if condition, we check if the element is not null.

$ dotnet run

Hello John!

Hello Nelly!

Hello there!

Hello George!
J Scott
  • 781
  • 9
  • 12
  • Thanks, but I'm afraid that won't work for our usecase, because we want the templates to be as simple as possible for our users to create. I added a few more details to the question to clarify. – RoadieRich Jul 22 '23 at 01:21
  • Then this becomes less a code problem and more a user experience issue. I'd say parse the user-supplied template for values as part of the upload and ask the user to supply a default for each one in their template. you could also fill null values with a placeholder (assuming they are all strings) like `ERROR` to get the outcome you want, but you would need to inspect the input before running the template – J Scott Jul 24 '23 at 19:18