From e1555e35585a5059fb9afa23e7b7592b3bfe947c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Ros?= Date: Wed, 10 Feb 2021 11:10:58 -0800 Subject: [PATCH] Define fallback scope in TemplateOptions (#263) --- Fluid.Tests/TemplateContextTests.cs | 24 +++++++++++++++++++++++- Fluid/TemplateContext.cs | 3 ++- Fluid/TemplateOptions.cs | 5 +++++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/Fluid.Tests/TemplateContextTests.cs b/Fluid.Tests/TemplateContextTests.cs index e0ce1a23..fcacaff8 100644 --- a/Fluid.Tests/TemplateContextTests.cs +++ b/Fluid.Tests/TemplateContextTests.cs @@ -1,4 +1,5 @@ -using System; +using Fluid.Values; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -28,5 +29,26 @@ private static async Task Register() var templateContext = new TemplateContext(); templateContext.Options.MemberAccessStrategy.Register(typeof(TestClass)); } + + + [Fact] + public void ScopeShouldFallbackToTemplateOptions() + { + var parser = new FluidParser(); + + parser.TryParse("{{ p.NaMe }}", out var template, out var error); + + var options = new TemplateOptions(); + options.Scope.SetValue("o1", new StringValue("o1")); + options.Scope.SetValue("o2", new StringValue("o2")); + + var context = new TemplateContext(options); + context.SetValue("o2", "new o2"); + context.SetValue("o3", "o3"); + + Assert.Equal("o1", context.GetValue("o1").ToStringValue()); + Assert.Equal("new o2", context.GetValue("o2").ToStringValue()); + Assert.Equal("o3", context.GetValue("o3").ToStringValue()); + } } } diff --git a/Fluid/TemplateContext.cs b/Fluid/TemplateContext.cs index b2c69a8c..da45d833 100644 --- a/Fluid/TemplateContext.cs +++ b/Fluid/TemplateContext.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Globalization; +using System.Threading.Tasks; namespace Fluid { @@ -33,7 +34,7 @@ public TemplateContext(TemplateOptions options) { Options = options; - LocalScope = new Scope(); + LocalScope = new Scope(options.Scope); LocalScope.SetValue("empty", NilValue.Empty); LocalScope.SetValue("blank", StringValue.Empty); diff --git a/Fluid/TemplateOptions.cs b/Fluid/TemplateOptions.cs index f009fd08..871fc237 100644 --- a/Fluid/TemplateOptions.cs +++ b/Fluid/TemplateOptions.cs @@ -45,6 +45,11 @@ public class TemplateOptions /// public FilterCollection Filters { get; } = new FilterCollection(); + /// + /// Gets a scope that is available in all the templates. + /// + public Scope Scope { get; } = new Scope(); + /// /// Gets the list of value converters. ///