Ignoring errors in Scriban

231 Views Asked by At

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.

1

There are 1 best solutions below

2
On

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!