示例#1
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (FluidTemplate.TryParse(Template, out var template))
            {
                var templateContext = new TemplateContext();
                templateContext.SetValue("model", Model);
                output.Content.SetHtmlContent(template.Render(templateContext));
            }

            base.Process(context, output);
        }
示例#2
0
        public async Task ShouldEvaluateStringValue()
        {
            FluidTemplate.TryParse("{{ x }}", out var template, out var messages);
            var context = new TemplateContext();

            context.SetValue("x", "abc");

            var result = await template.RenderAsync(context);

            Assert.Equal("abc", result);
        }
示例#3
0
        public static IRuleBuilderOptions <T, string?> Liquid <T>(this IRuleBuilder <T, string?> ruleBuilder)
        {
            return(ruleBuilder.Must(value =>
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    return true;
                }

                return FluidTemplate.TryParse(value, out _);
            }).WithMessage(Texts.ValidationLiquid));
        }
示例#4
0
        public void ShouldParseIntegralNumbers(string source, string expected)
        {
            var result = FluidTemplate.TryParse(source, out var template, out var errors);

            Assert.True(result, String.Join(", ", errors));
            Assert.NotNull(template);
            Assert.Empty(errors);

            var rendered = template.Render();

            Assert.Equal(expected, rendered);
        }
示例#5
0
        public AbstractXmlTemplate(TDocument document) : base(document)
        {
            this.PrepareTemplate();

            var stringTemplate = this.GetStringTemplate();

            if (!FluidTemplate.TryParse(stringTemplate, out var fluidTemplate, out var errors))
            {
                throw new SyntaxErrorException(errors.Aggregate((x, y) => x + "\n" + y));
            }
            this.TextTemplate = fluidTemplate;
        }
        private async Task CheckAsync(string source, string expected, Action <TemplateContext> init = null)
        {
            FluidTemplate.TryParse(source, out var template, out var messages);

            var context = new TemplateContext();

            init?.Invoke(context);

            var result = await template.RenderAsync(context);

            Assert.Equal(expected, result);
        }
示例#7
0
        public async Task TemplateIsRendered()
        {
            var regressions = new List <Regression>();

            regressions.Add(new Regression
            {
                PreviousResult = new BenchmarksResult
                {
                    Id          = 1,
                    Excluded    = false,
                    DateTimeUtc = DateTime.UtcNow,
                    Session     = "1234",
                    Scenario    = "Json",
                    Description = "Json aspnet-citrine-lin",
                    Document    = File.ReadAllText("assets/benchmarkresult1.json")
                },
                CurrentResult = new BenchmarksResult
                {
                    Id          = 2,
                    Excluded    = false,
                    DateTimeUtc = DateTime.UtcNow,
                    Session     = "1235",
                    Scenario    = "Json",
                    Description = "Json aspnet-citrine-lin",
                    Document    = File.ReadAllText("assets/benchmarkresult2.json")
                },
                Change            = 1000,
                StandardDeviation = 1,
                Average           = 10
            });

            var report = new Report
            {
                Regressions = regressions
            };

            var template = File.ReadAllText("assets/template.fluid");

            var parseIsSuccessful = FluidTemplate.TryParse(template, out var fluidTemplate, out var errors);

            Assert.True(parseIsSuccessful);

            var context = new TemplateContext {
                Model = report
            };

            var body = await fluidTemplate.RenderAsync(context);

            _output.WriteLine(body);

            Assert.NotEmpty(body);
        }
示例#8
0
        private static void Main(string[] args)
        {
            var app = new CommandLineApplication {
                Name = "dynamo2terraform"
            };

            app.HelpOption("-?|-h|--help");

            var inputFilePathOption = app.Option("-i|--input <path>",
                                                 "The path to the input C# DynamoDB Model decorated with DynamoDBAttributes for parsing",
                                                 CommandOptionType.SingleValue);

            var templateFilePathOption = app.Option("-t|--template <path>",
                                                    "The path to the liquid template to be used for generating the output",
                                                    CommandOptionType.SingleValue);

            app.OnExecute(() => {
                if (!inputFilePathOption.HasValue() || !File.Exists(inputFilePathOption.Value()))
                {
                    Console.WriteLine("Could not find Input file at the path provided");
                    return(0);
                }

                if (!templateFilePathOption.HasValue() || !File.Exists(templateFilePathOption.Value()))
                {
                    Console.WriteLine("Could not find Liquid template file at path provided");
                    return(0);
                }

                var tree  = ClassLoader.GetSyntaxTreeFromPath(inputFilePathOption.Value());
                var table = DynamoParserService.Parse(tree);

                var liquidTemplate = File.ReadAllText(templateFilePathOption.Value());


                IEnumerable <string> errors;
                if (FluidTemplate.TryParse(liquidTemplate, out var template, out errors))
                {
                    var context = new TemplateContext();
                    context.MemberAccessStrategy.Register(typeof(DynamoDbTable));                     // Allows any public property of the model to be used
                    context.MemberAccessStrategy.Register(typeof(DynamoDbAttribute));
                    context.MemberAccessStrategy.Register(typeof(DynamoDbGlobalSecondaryIndex));
                    context.SetValue("table", table);

                    Console.WriteLine(template.Render(context));
                }

                return(0);
            });

            app.Execute(args);
        }
示例#9
0
        protected override void PrepareTemplate()
        {
            this.TemplateDocument.Compile();

            this.TemplateDocument.Flush();

            var mainContentText = this.TemplateDocument.GetEntryTextReader(this.TemplateDocument.MainContentEntryPath).ReadToEnd();

            if (!FluidTemplate.TryParse(mainContentText, out this._fluidTemplate, out var errors))
            {
                throw new SyntaxErrorException(errors.Aggregate((x, y) => x + "\n" + y));
            }
        }
示例#10
0
        private async Task CheckAsync(string source, string expected, Action <TemplateContext> init = null)
        {
            FluidTemplate.TryParse(source, out var template, out var messages);

            var context = new TemplateContext();

            context.MemberAccessStrategy.Register(new { name = "product 1", price = 1 }.GetType());
            init?.Invoke(context);

            var result = await template.RenderAsync(context);

            Assert.Equal(expected, result);
        }
示例#11
0
文件: Program.cs 项目: rhwy/humid
        public string RenderTemplate(Context context, string name, object model)
        {
            var source = RenderTemplate(context, name);

            if (FluidTemplate.TryParse(source, out var template))
            {
                var templateContext = new TemplateContext();
                templateContext.MemberAccessStrategy.Register(model.GetType()); // Allows any public property of the model to be used
                templateContext.SetValue("p", model);

                return(template.Render(templateContext));
            }
            return(null);
        }
示例#12
0
        public async Task ShouldEvaluateAsyncMember()
        {
            FluidTemplate.TryParse("{{ Content.Foo }}{{ Content.Baz }}", out var template, out var messages);

            var context = new TemplateContext();

            context.SetValue("Content", new Content());
            context.MemberAccessStrategy.Register <Content, string>("Foo", async(obj, name) => { await Task.Delay(100); return("Bar"); });
            context.MemberAccessStrategy.Register <Content, string>(async(obj, name) => { await Task.Delay(100); return(name); });

            var result = await template.RenderAsync(context);

            Assert.Equal("BarBaz", result);
        }
示例#13
0
        public async Task ShouldSetFactoryValue()
        {
            FluidTemplate.TryParse("{{ Test }}", out var template, out var messages);
            bool set     = false;
            var  context = new TemplateContext();

            context.SetValue("Test", () => { set = true; return(set); });

            Assert.False(set);
            var result = await template.RenderAsync(context);

            Assert.Equal("true", result);
            Assert.True(set);
        }
示例#14
0
        public async Task ModelIsUsedAsFallback()
        {
            var source   = "hello {{ firstname }} {{ lastname }}";
            var expected = "hello sebastien ros";

            FluidTemplate.TryParse(source, out var template, out var messages);
            var context = new TemplateContext(new { lastname = "ros" });

            context.SetValue("firstname", "sebastien");

            var result = await template.RenderAsync(context);

            Assert.Equal(expected, result);
        }
示例#15
0
        /// <summary>
        /// implementing operate on rows (instead of row) to allow loading of external (file based) templates first
        /// </summary>
        /// <param name="rows"></param>
        /// <returns></returns>
        public override IEnumerable <IRow> Operate(IEnumerable <IRow> rows)
        {
            if (!Run)
            {
                yield break;
            }

            var key = string.Join(':', Context.Process.Id, Context.Entity.Alias, Context.Field.Alias, Context.Operation.Method, Context.Operation.Index);

            if (!_memoryCache.TryGetValue(key, out CachedFluidTransform transform))
            {
                transform = new CachedFluidTransform();

                var fileBasedTemplate = Context.Process.Templates.FirstOrDefault(t => t.Name == Context.Operation.Template);

                if (fileBasedTemplate != null)
                {
                    Context.Operation.Template = fileBasedTemplate.Content;
                }

                var input   = MultipleInput();
                var matches = Context.Entity.GetFieldMatches(Context.Operation.Template);
                transform.Input = input.Union(matches).ToArray();

                if (FluidTemplate.TryParse(Context.Operation.Template, out transform.Template))
                {
                    // any changes to content item will invalidate cache
                    _memoryCache.Set(key, transform, _signal.GetToken(Common.GetCacheKey(Context.Process.Id)));
                }
                else
                {
                    Context.Error("Failed to parse fluid template.");
                    Utility.CodeToError(Context, Context.Operation.Template);
                    yield break;
                }
            }

            var context = new TemplateContext();

            foreach (var row in rows)
            {
                foreach (var field in transform.Input)
                {
                    context.SetValue(field.Alias, row[field]);
                }
                row[Context.Field] = _convert(transform.Template.Render(context));
                yield return(row);
            }
        }
示例#16
0
        public async Task ShouldEvaluateInheritedObjectProperty()
        {
            FluidTemplate.TryParse("{{ e.Name }} {{ e.Salary }}", out var template, out var messages);

            var context = new TemplateContext();

            context.SetValue("e", new Employee {
                Name = "John", Salary = 550
            });
            context.MemberAccessStrategy.Register <Employee>();

            var result = await template.RenderAsync(context);

            Assert.Equal("John 550", result);
        }
示例#17
0
        public async Task ShouldEvaluateObjectProperty()
        {
            FluidTemplate.TryParse("{{ p.Name }}", out var template, out var messages);

            var context = new TemplateContext();

            context.SetValue("p", new Person {
                Name = "John"
            });
            context.MemberAccessStrategy.Register <Person>();

            var result = await template.RenderAsync(context);

            Assert.Equal("John", result);
        }
示例#18
0
        public async Task IgonreCasing()
        {
            FluidTemplate.TryParse("{{ p.NaMe }}", out var template, out var messages);

            var context = new TemplateContext();

            context.SetValue("p", new Person {
                Name = "John"
            });
            context.MemberAccessStrategy.IgnoreCasing = true;
            context.MemberAccessStrategy.Register <Person>();

            var result = await template.RenderAsync(context);

            Assert.Equal("John", result);
        }
示例#19
0
        public async Task ShouldNotAllowNotRegisteredInterfaceMembers()
        {
            TemplateContext.GlobalMemberAccessStrategy.Register <IAnimal>();

            FluidTemplate.TryParse("{{ p.Name }}", out var template, out var messages);

            var context = new TemplateContext();

            context.SetValue("p", new Dog {
                Name = "Rex"
            });

            var result = await template.RenderAsync(context);

            Assert.Equal("", result);
        }
示例#20
0
        public async Task ShouldRegisterValueMappingWithInterface()
        {
            FluidValue.ValueConverters.Add(x => x is IPet pet ? new PetValue(pet) : null);

            FluidTemplate.TryParse("{{ p.Name }}", out var template, out var messages);

            var context = new TemplateContext();

            context.SetValue("p", new Dog {
                Name = "Rex"
            });

            var result = await template.RenderAsync(context);

            Assert.Equal("Rex", result);
        }
示例#21
0
        public async Task ShouldEvaluateObjectPropertyWhenInterfaceRegisteredAsGlobal()
        {
            TemplateContext.GlobalMemberAccessStrategy.Register <IAnimal>();

            FluidTemplate.TryParse("{{ p.Age }}", out var template, out var messages);

            var context = new TemplateContext();

            context.SetValue("p", new Dog {
                Age = 12
            });

            var result = await template.RenderAsync(context);

            Assert.Equal("12", result);
        }
        public string Run(object arguments)
        {
            var source = TemplateManagement.Read("FluidDemo\\template.html");

            if (!FluidTemplate.TryParse(source, out var template))
            {
                throw new Exception();
            }

            var context = new TemplateContext();

            context.MemberAccessStrategy.Register(arguments.GetType());
            context.SetValue("p", arguments);

            return(template.Render(context));
        }
示例#23
0
        public async Task IncludeParamsShouldNotBeSetInTheParentTemplate()
        {
            var source   = @"{% include 'Partials', color: 'red', shape: 'circle' %}
{% assign color = 'blue' %}";
            var expected = @"Partial Content
color: 'red'
shape: 'circle'";

            FluidTemplate.TryParse(source, out var template, out var messages);
            var context = new TemplateContext
            {
                FileProvider = new MockFileProvider("Partials")
            };
            var result = await template.RenderAsync(context);

            Assert.Equal(expected, result);
        }
示例#24
0
        public void DirectModelTest()
        {
            var model  = new { Firstname = "Jacek", Lastname = "Sasin" };
            var source = "Hello {{ Firstname }} {{ Lastname }}";

            if (FluidTemplate.TryParse(source, out var template))
            {
                var context = new TemplateContext();
                foreach (var property in model.GetType().GetProperties())
                {
                    context.SetValue(property.Name, property.GetValue(model));
                }
                var result = template.Render(context);

                result.Should().Be("Hello Jacek Sasin");
            }
        }
示例#25
0
        public async Task ShouldNotAllowNotRegisteredMember()
        {
            FluidTemplate.TryParse("{{ c.Director.Name }} {{ c.Director.Salary }}", out var template, out var messages);

            var context = new TemplateContext();

            context.SetValue("c", new Company {
                Director = new Employee {
                    Name = "John", Salary = 550
                }
            });
            context.MemberAccessStrategy.Register <Company>();

            var result = await template.RenderAsync(context);

            Assert.Equal(" ", result);
        }
示例#26
0
        public void ShouldBeAbleToCompareNilValues()
        {
            // [1, 2, 3] | map will return [nil, nil, nil] then | uniq will try to call NilValue.GetHashCode()

            var model = new
            {
                Doubles = new List <double> {
                    1.1, 2.2, 3.3
                }
            };

            var template = "{{Doubles |map |uniq}}";

            if (FluidTemplate.TryParse(template, out var result))
            {
                result.Render(new TemplateContext(model));
            }
        }
示例#27
0
        public async Task AsyncFiltersAreEvaluated()
        {
            var source = "{% assign result = 'abcd' | query: 'efg' %}{%for x in result %}{{ x }}{%endfor%}";

            FluidTemplate.TryParse(source, out var template, out var messages);

            var context = new TemplateContext();

            context.Filters.AddAsyncFilter("query", async(input, arguments, ctx) =>
            {
                await Task.Delay(10);
                return(FluidValue.Create(input.ToStringValue() + arguments.At(0).ToStringValue()));
            });

            var result = await template.RenderAsync(context);

            Assert.Equal("abcdefg", result);
        }
示例#28
0
        public async Task NumbersAreFormattedUsingCulture()
        {
            var source     = "{{ 1234.567 }}";
            var expectedFR = "1234,567";
            var expectedUS = "1234.567";

            FluidTemplate.TryParse(source, out var template, out var messages);
            var context = new TemplateContext();

            context.CultureInfo = new CultureInfo("en-US");
            var resultUS = await template.RenderAsync(context);

            context.CultureInfo = new CultureInfo("fr-FR");
            var resultFR = await template.RenderAsync(context);

            Assert.Equal(expectedFR, resultFR);
            Assert.Equal(expectedUS, resultUS);
        }
示例#29
0
        public void ShouldNotRegisterModelType()
        {
            var model = new
            {
                name = "Tobi"
            };

            var source = "{{name}}";

            FluidTemplate.TryParse(source, out var template);
            var rendered = template.Render(new TemplateContext(model, false));

            Assert.Equal("", rendered);

            rendered = template.Render(new TemplateContext(model, true));

            Assert.Equal("Tobi", rendered);
        }
示例#30
0
        public void RenderSimpleText()
        {
            string text = "Hello, {{name}} ";

            string name1 = "catcher wong";
            string name2 = "Catcher Wong";

            if (FluidTemplate.TryParse(text, out var template))
            {
                var context1 = new TemplateContext();
                context1.SetValue("name", name1);
                Console.WriteLine(template.Render(context1));

                var context2 = new TemplateContext();
                context2.SetValue("Name", name2);
                Console.WriteLine(template.Render(context2));
            }
        }