Handlebars.Net If 条件助手

Max*_*ann 3 c# handlebarshelper handlebars.net

我尝试编写一个 Handlebar.Net 助手,其工作方式类似于 Equals。\n助手应该像这样使用

\n\n
{{#eq name "Foo"}}\n    true\n{{else}}\n    false\n{{/eq}}\n
Run Code Online (Sandbox Code Playgroud)\n\n

但我不知道如何实现这个助手。JS中有这样的示例,但我无法\xc2\xb4t 找到 C# 的示例。

\n\n

我的第一枪是:

\n\n
Handlebars.RegisterHelper("#eq", (output, context, data) =>\n{\n    if (data.Length != 2)\n        output.WriteSafeString("false");\n\n    output.WriteSafeString(data[0].Equals(data[1]));\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

但这只是将 True 或 False 写入我的文件中。

\n

Max*_*ann 5

我\xc2\xb4ve找到了解决方案:

\n\n
Handlebars.RegisterHelper(Equals, (output, options, context, data) => \n{\n    if (data.Length != 2)\n        options.Inverse(output, null);\n\n    if (data[0].Equals(data[1]))\n        options.Template(output, null);\n    else\n        options.Inverse(output, null);\n});\nHandlebars.RegisterHelper(LowerThan, (output, options, context, data) =>\n{\n    IntegerOperation(LowerThan, ref output, ref options, ref data);\n});\n\nHandlebars.RegisterHelper(GreaterThan, (output, options, context, data) =>\n{\n    IntegerOperation(GreaterThan, ref output, ref options, ref data);\n});\n\nHandlebars.RegisterHelper(LowerEquals, (output, options, context, data) =>\n{\n    IntegerOperation(LowerEquals, ref output, ref options, ref data);\n});\n\nHandlebars.RegisterHelper(GreaterEquals, (output, options, context, data) =>\n{\n    IntegerOperation(GreaterEquals, ref output, ref options, ref data);\n});\n\n\nprivate static void IntegerOperation(string operation, ref System.IO.TextWriter output, ref HelperOptions options, ref object[] data)\n{\n    if (data.Length != 2)\n    {\n        options.Inverse(output, null);\n        return;\n    }\n\n    if (!int.TryParse(data[0].ToString(), out int leftValue))\n    {\n        options.Inverse(output, null);\n        return;\n    }\n\n    if (!int.TryParse(data[1].ToString(), out int rightValue))\n    {\n        options.Inverse(output, null);\n        return;\n    }\n\n    switch (operation)\n    {\n        case "lt":\n            if (leftValue < rightValue)\n                options.Template(output, null);\n            else\n                options.Inverse(output, null);\n            break;\n        case "le":\n            if (leftValue <= rightValue)\n                options.Template(output, null);\n            else\n                options.Inverse(output, null);\n            break;\n        case "gt":\n            if (leftValue > rightValue)\n                options.Template(output, null);\n            else\n                options.Inverse(output, null);\n            break;\n        case "ge":\n            if (leftValue >= rightValue)\n                options.Template(output, null);\n            else\n                options.Inverse(output, null);\n            break;\n        default:\n            break;\n    }\n
Run Code Online (Sandbox Code Playgroud)\n