Exemplo n.º 1
0
        public HbsRenderer(IServiceProvider services, IHandlebars handlebars, IOptions <HandlebarsViewEngineOptions> options, IExpressionCache expressionCache)
        {
            _options         = options.Value;
            _services        = services.CreateScope().ServiceProvider;
            _expressionCache = expressionCache;
            _handlebars      = handlebars;

            var helpersAction = _options.RegisterHelpers;

            if (helpersAction != null)
            {
                var helpers = new HelperList();
                helpersAction.Invoke(helpers);

                foreach (var helper in helpers)
                {
                    var h = _services.GetService(helper).Cast <HandlebarsBaseHelper>();
                    switch (h.HelperType)
                    {
                    case HelperType.HandlebarsHelper:
                        _handlebars.RegisterHelper(h.HelperName, h.HandlebarsHelper);
                        break;

                    case HelperType.HandlebarsBlockHelper:
                        _handlebars.RegisterHelper(h.HelperName, h.HandlebarsBlockHelper);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }
            }
        }
Exemplo n.º 2
0
        public static void Register(IHandlebars handlebarsContext)
        {
            handlebarsContext.RegisterHelper("Regex.Match", (writer, context, arguments) =>
            {
                (string stringToProcess, string regexPattern, object defaultValue) = ParseArguments(arguments);

                Match match = Regex.Match(stringToProcess, regexPattern);

                if (match.Success)
                {
                    writer.WriteSafeString(match.Value);
                }
                else if (defaultValue != null)
                {
                    writer.WriteSafeString(defaultValue);
                }
            });

            handlebarsContext.RegisterHelper("Regex.Match", (writer, options, context, arguments) =>
            {
                (string stringToProcess, string regexPattern, object defaultValue) = ParseArguments(arguments);

                var regex       = new Regex(regexPattern);
                var namedGroups = RegexUtils.GetNamedGroups(regex, stringToProcess);
                if (namedGroups.Any())
                {
                    options.Template(writer, namedGroups);
                }
                else if (defaultValue != null)
                {
                    options.Template(writer, defaultValue);
                }
            });
        }
        public static void Register(IHandlebars handlebarsContext)
        {
            handlebarsContext.RegisterHelper("Linq", (writer, context, arguments) =>
            {
                (JToken valueToProcess, string linqStatement) = ParseArguments(arguments);

                try
                {
                    object result = ExecuteDynamicLinq(valueToProcess, linqStatement);
                    writer.WriteSafeString(result);
                }
                catch (ParseException)
                {
                    // Ignore ParseException
                }
            });

            handlebarsContext.RegisterHelper("Linq", (writer, options, context, arguments) =>
            {
                (JToken valueToProcess, string linqStatement) = ParseArguments(arguments);

                try
                {
                    var result = ExecuteDynamicLinq(valueToProcess, linqStatement);
                    options.Template(writer, result);
                }
                catch (ParseException)
                {
                    // Ignore ParseException
                }
            });
        }
Exemplo n.º 4
0
        public static void Register(IHandlebars handlebarsContext)
        {
            handlebarsContext.RegisterHelper("JsonPath.SelectToken", (writer, context, arguments) =>
            {
                (JObject valueToProcess, string jsonPath) = ParseArguments(arguments);

                try
                {
                    var result = valueToProcess.SelectToken(jsonPath);
                    writer.WriteSafeString(result);
                }
                catch (JsonException)
                {
                    // Ignore JsonException
                }
            });

            handlebarsContext.RegisterHelper("JsonPath.SelectTokens", (writer, options, context, arguments) =>
            {
                (JObject valueToProcess, string jsonPath) = ParseArguments(arguments);

                try
                {
                    var values = valueToProcess.SelectTokens(jsonPath);
                    if (values != null)
                    {
                        options.Template(writer, values.ToDictionary(value => value.Path, value => value));
                    }
                }
                catch (JsonException)
                {
                    // Ignore JsonException
                }
            });
        }
Exemplo n.º 5
0
        public void Setup()
        {
            _handlebars = Handlebars.Create();

            _handlebars.RegisterHelper("pow1", (output, context, arguments) => output.WriteSafeString(((int)arguments[0] * (int)arguments[0]).ToString()));
            _handlebars.RegisterHelper("pow2", (output, context, arguments) => output.WriteSafeString(((int)arguments[0] * (int)arguments[0]).ToString()));
            _handlebars.RegisterHelper("pow5", (output, options, context, arguments) => output.WriteSafeString(((int)arguments[0] * (int)arguments[0]).ToString()));
        }
Exemplo n.º 6
0
 internal void Helpers(IHandlebars handlebars)
 {
     handlebars.RegisterHelper("command-ctor", (writer, context, parameters) => { RenderCommandConstructor(parameters, context, writer); });
     handlebars.RegisterHelper("command-exec", (writer, context, parameters) => { RenderCommandFunctions(parameters, writer); });
     handlebars.RegisterHelper("command-can-exec", (writer, context, parameters) => { RenderCommandCanExecute(parameters, writer); });
     handlebars.RegisterHelper("command-type", (writer, context, parameters) => { RenderCommandProperty(writer); });
     handlebars.RegisterHelper("base", (writer, context, parameters) => { RenderBaseClass(parameters, writer); });
 }
Exemplo n.º 7
0
        public HandlebarsConverter(TopLevelConfig topLevelConfig)
        {
            this.topLevelConfig = topLevelConfig;

            handlebars = Handlebars.Create();

            handlebars.RegisterHelper("include", IncludeHelper);
            handlebars.RegisterHelper("markdown", MarkdownHelper);
            handlebars.RegisterHelper("set", SetHelper);
            handlebars.RegisterHelper("ifeq", IfEqHelper);
        }
Exemplo n.º 8
0
        public TemplateEngine(IEnumerable <string> templates)
        {
            this.engine = HandlebarsDotNet.Handlebars.Create(new HandlebarsConfiguration
            {
                ThrowOnUnresolvedBindingExpression = true
            });

            engine.RegisterHelper("concat", (writer, context, args) =>
            {
                writer.WriteSafeString(string.Concat(args));
            });

            engine.RegisterHelper("pascalCase", (writer, context, args) =>
            {
                writer.WriteSafeString(args[0].ToString().ToPascalCase());
            });

            engine.RegisterHelper("camelCase", (writer, context, args) =>
            {
                writer.WriteSafeString(args[0].ToString().ToCamelCase());
            });

            engine.RegisterHelper("replace", (writer, context, args) =>
            {
                var toReplace     = args[1].ToString();
                var toReplaceWith = args[2].ToString();

                writer.WriteSafeString(args[0].ToString().Replace(toReplace, toReplaceWith));
            });

            engine.Configuration.TextEncoder = new NullEncoder();
            //engine.RegisterHelper("render", (w, c, a) =>
            //{
            //    if (c is Models.TypeViewModel typeVm)
            //    {
            //        // this is the typerefcontext
            //        w.WriteSafeString("Type");
            //        return;
            //    }
            //    if (c is Models.TypeReferenceModel typeRef)
            //    {
            //        // this is the typerefcontext
            //        w.WriteSafeString("TypeReference_" + typeRef.ScalerType.ToString());
            //        return;
            //    }
            //});

            foreach (var templatePath in templates)
            {
                var templateContents = LoadTemplate(templatePath);
                ProcessTemplate(templateContents);
            }
        }
        public static void Register(IHandlebars handlebarsContext)
        {
            handlebarsContext.RegisterHelper("Random", (writer, context, arguments) =>
            {
                object value = GetRandomValue(arguments);
                writer.Write(value);
            });

            handlebarsContext.RegisterHelper("Random", (writer, options, context, arguments) =>
            {
                object value = GetRandomValue(arguments);
                options.Template(writer, value);
            });
        }
Exemplo n.º 10
0
        public static void Register(IHandlebars handlebarsContext, IFileSystemHandler fileSystemHandler)
        {
            handlebarsContext.RegisterHelper("File", (writer, context, arguments) =>
            {
                string value = ParseArgumentAndReadFileFragment(handlebarsContext, context, fileSystemHandler, arguments);
                writer.Write(value);
            });

            handlebarsContext.RegisterHelper("File", (writer, options, context, arguments) =>
            {
                string value = ParseArgumentAndReadFileFragment(handlebarsContext, context, fileSystemHandler, arguments);
                options.Template(writer, value);
            });
        }
Exemplo n.º 11
0
        public static void Register(IHandlebars handlebarsContext)
        {
            handlebarsContext.RegisterHelper("Xeger", (writer, context, arguments) =>
            {
                string value = ParseArgumentAndGenerate(arguments);
                writer.Write(value);
            });

            handlebarsContext.RegisterHelper("Xeger", (writer, options, context, arguments) =>
            {
                string value = ParseArgumentAndGenerate(arguments);
                options.Template(writer, value);
            });
        }
Exemplo n.º 12
0
        private void RegisterHelpers(IHandlebars hb, Language language, GeneratorOptions options)
        {
            HelperFactory.RegisterAllForType(hb, typeof(DefaultHelpers), null);
            HelperFactory.RegisterAllForType(hb, language.GetType(), language);

            hb.RegisterHelper("clientName", (writer, context, parameters) => { writer.Write(options.ClientName); });
        }
Exemplo n.º 13
0
        internal static void RegisterAllForType(IHandlebars hb, Type type, object instance)
        {
            var helpers = CreateHelpersForType(type, instance);

            foreach (var(name, helper) in helpers)
            {
                hb.RegisterHelper(name, helper);
            }

            var blockHelpers = CreateBlockHelpersForType(type, instance);

            foreach (var(name, helper) in blockHelpers)
            {
                hb.RegisterHelper(name, helper);
            }
        }
Exemplo n.º 14
0
        private void RegisterHandlebarsHelpers()
        {
            _handlebars.RegisterHelper("lt", (writer, context, args) =>
            {
                if (args.Length != 2)
                {
                    writer.Write("lt:Requires exactly two arguments");
                    return;
                }

                if (args[0] == null || args[0].GetType().Name == "UndefinedBindingResult")
                {
                    writer.Write("lt:First argument is undefined");
                    return;
                }

                if (args[1] == null || args[1].GetType().Name == "UndefinedBindingResult")
                {
                    writer.Write("lt:Second argument is undefined");
                    return;
                }

                var val1 = double.Parse(args[0].ToString());
                var val2 = double.Parse(args[1].ToString());
                if (val1 < val2)
                {
                    writer.Write(true);
                }
            });
        }
Exemplo n.º 15
0
        public static void RegisterContentTokens(this IHandlebars handlebars)
        {
            // Renders a slug for the current content item. Do not use to represent the url
            // as the content item as it might be different than the computed slug.
            handlebars.RegisterHelper("slug", (output, context, arguments) =>
            {
                IServiceProvider serviceProvider = context.ServiceProvider;
                var contentManager = serviceProvider.GetRequiredService <IContentManager>();
                var slugService    = serviceProvider.GetRequiredService <ISlugService>();

                ContentItem contentItem = context.Content;

                string title = contentManager.PopulateAspect <ContentItemMetadata>(contentItem).DisplayText;

                var slug = slugService.Slugify(title);
                output.Write(slug);
            });

            // The "container" block helper redefines the context.Content property to
            // the container of the current context Content property. If the content doesn't
            // have a container then the inner template is not rendered.
            // Example: {{#container}}{{slug}}/{{/container}}{{slug}}, this will render the slug of the
            // container then the slug of the content item.
            handlebars.RegisterHelper("container", (output, options, context, arguments) =>
            {
                ContentItem contentItem = context.Content;

                string containerId = contentItem.Content?.ContainedPart?.ListContentItemId;

                if (containerId != null)
                {
                    IServiceProvider serviceProvider = context.ServiceProvider;
                    var contentManager = serviceProvider.GetRequiredService <IContentManager>();

                    var container = contentManager.GetAsync(containerId).GetAwaiter().GetResult();

                    if (container != null)
                    {
                        var previousContent = context.Content;
                        context.Content     = container;
                        options.Template(output, context);
                        context.Content = previousContent;
                    }
                }
            });
        }
        public void ArrayListProperties(IHandlebars handlebars)
        {
            var model = JsonDocument.Parse("[{\"Key\": \"Key1\", \"Value\": \"Val1\"},{\"Key\": \"Key2\", \"Value\": \"Val2\"}]");

            var source = "{{listProperties this}}";

            handlebars.RegisterHelper(new ListPropertiesHelper());
            var template = handlebars.Compile(source);

            var output = template(model);

            Assert.Equal("length", output);
        }
        public void JsonTestIfFalsy(IHandlebars handlebars)
        {
            var model = JsonDocument.Parse("{\"falsy\":false}");

            var source = "{{#if (not falsy)}}{{falsy}}{{/if}}";

            handlebars.RegisterHelper("not", (context, arguments) => !arguments.At <bool>(0));
            var template = handlebars.Compile(source);

            var output = template(model);

            Assert.Equal("False", output);
        }
Exemplo n.º 18
0
        public void ImplicitIDictionaryImplementationShouldNotThrowNullref()
        {
            // Arrange
            IHandlebars handlebars = Handlebars.Create();

            handlebars.RegisterHelper("foo", (writer, context, arguments) => { });
            var compile = handlebars.Compile(@"{{foo bar}}");
            var mock    = new MockDictionaryImplicitlyImplemented(new Dictionary <string, object> {
                { "bar", 1 }
            });

            // Act
            compile.Invoke(mock);
        }
        public void ObjectListProperties(IHandlebars handlebars)
        {
            var model = JsonDocument.Parse("{\"Key1\": \"Val1\", \"Key2\": \"Val2\"}");

            var source = "{{ListProperties this}}";

            handlebars.RegisterHelper(new ListPropertiesHelper());

            var template = handlebars.Compile(source);

            var output = template(model);

            Assert.Equal("Key1, Key2", output);
        }
Exemplo n.º 20
0
        public static void RegisterStandardTokens(this IHandlebars handlebars, IHttpContextAccessor httpContextAccessor)
        {
            handlebars.RegisterHelper("dateformat", (output, context, arguments) =>
            {
                var services    = httpContextAccessor.HttpContext.RequestServices;
                var clock       = services.GetRequiredService <IClock>();
                var siteService = services.GetRequiredService <ISiteService>();
                var site        = siteService.GetSiteSettingsAsync().GetAwaiter().GetResult();
                var timeZone    = TimeZoneInfo.FindSystemTimeZoneById(site.TimeZone);
                var now         = TimeZoneInfo.ConvertTime(clock.UtcNow, TimeZoneInfo.Utc, timeZone);

                var format = arguments[0].ToString();
                output.Write(now.ToString(format));
            });
        }
Exemplo n.º 21
0
        public static void RegisterStandardTokens(this IHandlebars handlebars)
        {
            handlebars.RegisterHelper("dateformat", (output, context, arguments) =>
            {
                IServiceProvider serviceProvider = context.ServiceProvider;
                var clock       = serviceProvider.GetRequiredService <IClock>();
                var siteService = serviceProvider.GetRequiredService <ISiteService>();
                var site        = siteService.GetSiteSettingsAsync().Result;
                var timeZone    = TimeZoneInfo.FindSystemTimeZoneById(site.TimeZone);
                var now         = TimeZoneInfo.ConvertTime(clock.UtcNow.UtcDateTime, TimeZoneInfo.Utc, timeZone);

                var format = arguments[0].ToString();
                output.Write(now.ToString(format));
            });
        }
Exemplo n.º 22
0
        public static void RegisterContentTokens(this IHandlebars handlebars)
        {
            handlebars.RegisterHelper("slug", (output, context, arguments) =>
            {
                IServiceProvider serviceProvider = context.ServiceProvider;
                var contentManager = serviceProvider.GetRequiredService <IContentManager>();

                ContentItem contentItem = context.Content;

                string title = contentManager.PopulateAspect(contentItem, new ContentItemMetadata()).DisplayText;

                var slug = title?.ToLower().Replace(" ", "-");
                output.Write(slug);
            });
        }
Exemplo n.º 23
0
 private static void AddHelpers(IHandlebars handlebars)
 {
     handlebars.RegisterHelper("asset",
                               (writer, context, arguments) => writer.Write("asset:" + string.Join("|", arguments)));
     handlebars.RegisterHelper("date",
                               (writer, context, arguments) => writer.Write("date:" + string.Join("|", arguments)));
     handlebars.RegisterHelper("tags",
                               (writer, context, arguments) => writer.Write("tags:" + string.Join("|", arguments)));
     handlebars.RegisterHelper("encode",
                               (writer, context, arguments) => writer.Write("encode:" + string.Join("|", arguments)));
     handlebars.RegisterHelper("url", (writer, context, arguments) => writer.Write("url:" + string.Join("|", arguments)));
     handlebars.RegisterHelper("excerpt", (writer, context, arguments) => writer.Write("url:" + string.Join("|", arguments)));
 }
Exemplo n.º 24
0
 private static void AddHelpers(IHandlebars handlebars)
 {
     handlebars.RegisterHelper("asset",
         (writer, context, arguments) => writer.Write("asset:" + string.Join("|", arguments)));
     handlebars.RegisterHelper("date",
         (writer, context, arguments) => writer.Write("date:" + string.Join("|", arguments)));
     handlebars.RegisterHelper("tags",
         (writer, context, arguments) => writer.Write("tags:" + string.Join("|", arguments)));
     handlebars.RegisterHelper("encode",
         (writer, context, arguments) => writer.Write("encode:" + string.Join("|", arguments)));
     handlebars.RegisterHelper("url", (writer, context, arguments) => writer.Write("url:" + string.Join("|", arguments)));
     handlebars.RegisterHelper("excerpt", (writer, context, arguments) => writer.Write("url:" + string.Join("|", arguments)));
 }
Exemplo n.º 25
0
 private void RegisterIfAndHelper(IHandlebars hbs)
 {
     hbs.RegisterHelper("ifand", (writer, options, context, arguments) =>
     {
         bool res = true;
         foreach (var arg in arguments)
         {
             res = res && HandlebarsUtils.IsTruthyOrNonEmpty(arg);
         }
         if (res)
         {
             options.Template(writer, (object)context);
         }
         else
         {
             options.Inverse(writer, (object)context);
         }
     });
 }
Exemplo n.º 26
0
 private void RegisterIfInHelper(IHandlebars hbs)
 {
     hbs.RegisterHelper("ifin", (writer, options, context, arguments) =>
     {
         bool res = false;
         if (arguments.Length > 1)
         {
             for (int i = 1; i < arguments.Length; i++)
             {
                 res = res || arguments[0].Equals(arguments[i]);
             }
         }
         if (res)
         {
             options.Template(writer, (object)context);
         }
         else
         {
             options.Inverse(writer, (object)context);
         }
     });
 }
Exemplo n.º 27
0
        private static void RegisterContainsHelper(IHandlebars hbs)
        {
            hbs.RegisterHelper("contains", (writer, options, context, arguments) =>
            {
                bool res = false;
                if (arguments != null && arguments.Length == 2)
                {
                    var arg1 = arguments[0].ToString();
                    var arg2 = arguments[1].ToString();
                    res      = arg2.Contains(arg1);
                }

                if (res)
                {
                    options.Template(writer, (object)context);
                }
                else
                {
                    options.Inverse(writer, (object)context);
                }
            });
        }
Exemplo n.º 28
0
 private static void registerHelpers(IHandlebars handlebars, string dialect)
 {
     handlebars.RegisterHelper("_ServerCurrentTime_", (writer, context, args) =>
     {
         if (dialect == "mssql")
         {
             writer.Write("getdate()");
         }
         else
         if (dialect == "mysql")
         {
             writer.Write("now()");
         }
         else
         if (dialect == "postgres")
         {
             writer.Write("current_time");
         }
         else
         {
             throw new Exception("BuhtaServer.registerHelpers(): неверный SQL-диалект '" + dialect + "'");
         }
     });
 }
 public static void RegisterHelper(string helperName, HandlebarsHelper helperFunction)
 {
     Instance.RegisterHelper(helperName, helperFunction);
 }
Exemplo n.º 30
0
        public HandlebarsPageRenderer(string templateHbs, IReadOnlyDictionary <string, string> partials, DocsSiteRouter router)
        {
            _templateHbs = templateHbs;
            _handlebars  = Handlebars.Create();
            _handlebars.RegisterHelper("link_to", (output, options, context, arguments) =>
            {
                if (arguments.Length != 1)
                {
                    throw new InvalidOperationException($"link_to requires one argument of type DisplayLink");
                }

                var target = arguments[0];

                string?url   = null;
                string?title = null;
                if (target is DisplayLink displayLink)
                {
                    title = displayLink.Title ?? "";
                    url   = displayLink.Link.Xref != null
                        ? router.GenerateRoute(displayLink.Link.Xref.Value)
                        : displayLink.Link.Uri;
                }

                if (url == null)
                {
                    url = "[TODO: MISSING LINK TARGET]";
                }

                options.Template(output, new
                {
                    title,
                    url
                });
            });

            _handlebars.RegisterHelper("xref", (output, options, context, arguments) =>
            {
                if (arguments.Length != 1)
                {
                    throw new InvalidOperationException($"xref requires one argument of type xref");
                }

                var target = arguments[0];

                string?url = null;

                if (target is string xrefStr)
                {
                    target = LinkParser.Parse(xrefStr);
                }

                if (target is Link link)
                {
                    if (link.IsExternal)
                    {
                        url = link.Uri;
                    }
                    else
                    {
                        target = link.Xref !.Value;
                    }
Exemplo n.º 31
0
        void RegisterInternal()
        {
            IHandlebars h = _services.Handlebars;

            h.RegisterHelper("Upper", (o, c, a) => o.Write(a[0].ToString().ToUpper()));
            h.RegisterHelper("Lower", (o, c, a) => o.Write(a[0].ToString().ToLower()));
            h.RegisterHelper("LocalTimeZoneInfoId", (o, c, a) => o.Write(TimeZoneInfo.Local.Id));
            h.RegisterHelper("SystemTimeZonesJson", (o, c, a) => Json(o, c, new Arguments(TimeZoneInfo.GetSystemTimeZones().ToDictionary())));
            h.RegisterHelper("DefaultDateFormat", (o, c, a) => o.Write(DateTimeSettings.DefaultDateFormat));
            h.RegisterHelper("DefaultTimeFormat", (o, c, a) => o.Write(DateTimeSettings.DefaultTimeFormat));
            h.RegisterHelper("DoLayout", (o, c, a) => { });
            h.RegisterHelper("SerializeTypeHandler", (o, c, a) => o.WriteSafeString(((Services)a[0]).TypeHandlers.Serialize((TypeHandlerBase)c["Services"])));
            h.RegisterHelper("Disabled", (o, c, a) => { if (IsTrue(a[0]))
                                                        {
                                                            o.Write("disabled");
                                                        }
                             });
            h.RegisterHelper("Checked", (o, c, a) => { if (IsTrue(a[0]))
                                                       {
                                                           o.Write("checked");
                                                       }
                             });
            h.RegisterHelper("nvl", (o, c, a) => o.Write(a[a[0] == null ? 1 : 0]));
            h.RegisterHelper("not", (o, c, a) => o.Write(IsTrue(a[0]) ? "False" : "True"));

            h.RegisterHelper(nameof(BaseUrl), (o, c, a) => o.WriteSafeString(BaseUrl));
            h.RegisterHelper(nameof(MenuItemActionLink), MenuItemActionLink);
            h.RegisterHelper(nameof(RenderJobDataMapValue), RenderJobDataMapValue);
            h.RegisterHelper(nameof(ViewBag), ViewBag);
            h.RegisterHelper(nameof(ActionUrl), ActionUrl);
            h.RegisterHelper(nameof(Json), Json);
            h.RegisterHelper(nameof(Selected), Selected);
            h.RegisterHelper(nameof(isType), isType);
            h.RegisterHelper(nameof(eachPair), eachPair);
            h.RegisterHelper(nameof(eachItems), eachItems);
            h.RegisterHelper(nameof(ToBase64), ToBase64);
            h.RegisterHelper(nameof(footer), footer);
            h.RegisterHelper(nameof(QuartzminVersion), QuartzminVersion);
            h.RegisterHelper(nameof(Logo), Logo);
            h.RegisterHelper(nameof(ProductName), ProductName);
        }