jehugaleahsa / mustache-sharp

An extension of the mustache text template engine for .NET.
The Unlicense
306 stars 80 forks source link

Duplicate output on custom tag #68

Closed PaulGrimshaw closed 7 years ago

PaulGrimshaw commented 7 years ago

I have written a custom tag to Url encode a provided string, following the UPPER CASE example in the README.

It works fine for a static piece of text:

[TestMethod]
        public void TestCompile_UrlEncode() {
            FormatCompiler compiler = new FormatCompiler();
            compiler.RegisterTag(new UrlEncodeTagDefinition(), true);
            const string format = @"{{#urlencode}}https://google.com{{/urlencode}}";
            Generator generator = compiler.Compile(format);

            string actual = generator.Render(new { });
            string expected = "https%3a%2f%2fgoogle.com";
            Assert.AreEqual(expected, actual, "Value field didn't work");
        }

But when i try with a template tag value, it works but renders the result twice:

        [TestMethod]
        public void TestCompile_UrlEncodeVariableText() {
            FormatCompiler compiler = new FormatCompiler();
            compiler.RegisterTag(new UrlEncodeTagDefinition(), true);

            const string format = @"{{#urlencode}}{{url}}{{/urlencode}}";
            Generator generator = compiler.Compile(format);

            string actual = generator.Render(new { url = "https://google.com" });
            string expected = "https%3a%2f%2fgoogle.com";
            Assert.AreEqual(expected, actual, "Value field didn't work");

            //RESULT: Assert.AreEqual failed. Expected:<https%3a%2f%2fgoogle.com>. Actual:https%3a%2f%2fgoogle.comhttps%3a%2f%2fgoogle.com>
        }

Custom tag:

public class UrlEncodeTagDefinition : ContentTagDefinition {
        public UrlEncodeTagDefinition()
            : base("urlencode") {
        }

        public override IEnumerable<NestedContext> GetChildContext(TextWriter writer,Scope keyScope,Dictionary<string, object> arguments,Scope contextScope) {
            NestedContext context = new NestedContext() {
                KeyScope = keyScope,
                Writer = new StringWriter(),
                WriterNeedsConsidated = true,
            };
            yield return context;
        } 

        public override IEnumerable<TagParameter> GetChildContextParameters() {
            return new TagParameter[] { new TagParameter("collection") };
        }

        public override string ConsolidateWriter(TextWriter writer, Dictionary<string, object> arguments) {
            return HttpUtility.UrlEncode(writer.ToString());
        }
    }
jehugaleahsa commented 7 years ago

You discovered a bug. It's been fixed and pushed to NuGet, version 0.2.10.0. Nice find.

PaulGrimshaw commented 7 years ago

Great, thanks for the rapid response.