public void Init() { var configuration = new HandlebarsConfiguration { ExpressionNameResolver = new UpperCamelCaseExpressionNameResolver() }; this.HandlebarsInstance = Handlebars.Create(configuration); }
public HandlebarsMvcView(string physicalpath, IHandlebars handlebars) { var templatePath = physicalpath; var version = HostingEnvironment.VirtualPathProvider.GetCacheKey(templatePath); var key = templatePath + "_" + version; render = compiledViews.GetOrAdd(key, (k) => { var compiledView = handlebars.CompileView(templatePath); return compiledView; }); }
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))); }
public HandlebarsMvcViewEngine(IHandlebars handlebars) { _handlebars = handlebars; // Define the location of the View file this.ViewLocationFormats = new string[] {"~/Views/{1}/{0}.hbs", "~/Views/{0}.hbs"}; this.PartialViewLocationFormats = new string[] {"~/Views/{1}/{0}.hbs", "~/Views/partials/{0}.hbs"}; this.MasterLocationFormats = new string[] { "~/Views/{1}/{0}.hbs", "~/Views/layouts/{0}.hbs" }; ; //Masters are referenced inside views }
public HumanizerHelpersTemplateTests() { _dateTimeServiceMock = new Mock <IDateTimeService>(); _dateTimeServiceMock.Setup(d => d.Now()).Returns(DateTimeNow); _dateTimeServiceMock.Setup(d => d.UtcNow()).Returns(DateTimeNow.ToUniversalTime); _handlebarsContext = Handlebars.Create(); _handlebarsContext.Configuration.FormatProvider = CultureInfo.InvariantCulture; HandlebarsHelpers.Register(_handlebarsContext, o => { o.DateTimeService = _dateTimeServiceMock.Object; }); }
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 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); }); }
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); }); }
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); }); }
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)); }); }
private static string ParseArgumentAndReadFileFragment(IHandlebars handlebarsContext, dynamic context, IFileSystemHandler fileSystemHandler, object[] arguments) { Check.Condition(arguments, args => args.Length == 1, nameof(arguments)); Check.NotNull(arguments[0], "arguments[0]"); switch (arguments[0]) { case string path: var templateFunc = handlebarsContext.Compile(path); string transformed = templateFunc(context); return(fileSystemHandler.ReadResponseBodyAsString(transformed)); } throw new NotSupportedException($"The value '{arguments[0]}' with type '{arguments[0]?.GetType()}' cannot be used in Handlebars File."); }
public static Templates Load(string languageName, IHandlebars hb) { string templates = Path.Combine( Path.GetDirectoryName(typeof(Templates).Assembly.Location), "Languages", languageName); Action <TextWriter, object> serviceClient = LoadTemplateFile(hb, templates, "ServiceClient.hb"); Action <TextWriter, object> model = LoadTemplateFile(hb, templates, "Model.hb"); Action <TextWriter, object> methodGroup = LoadTemplateFile(hb, templates, "MethodGroup.hb"); return(new Templates( (writer, m) => serviceClient(writer, m), (writer, m) => model(writer, m), (writer, m) => methodGroup(writer, m))); }
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); }); }
public Models() { _controllerContext = new ControllerContext(); _handlebars = HandlebarsDotNet.Handlebars.Create(); _vdd = new ViewDataDictionary(); // The view. Note that we're also testing for case-insensitivity (lastname is lowercase here, but not in the models). var funcView = _handlebars.Compile("Hello, {{FirstName}} {{lastname}}!"); _compiledView = new CompiledView(funcView, fileHash: null, layout: null); _hbsview = new HandlebarsView(_controllerContext, _compiledView, layouts: null); }
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)); }); }
/// <summary> /// Register all (default) or specific categories and use the prefix from the categories. /// </summary> /// <param name="handlebarsContext">The <see cref="IHandlebars"/>-context.</param> /// <param name="optionsCallback">The options callback.</param> public static void Register(IHandlebars handlebarsContext, Action <HandlebarsHelpersOptions> optionsCallback) { Guard.NotNull(optionsCallback, nameof(optionsCallback)); var options = new HandlebarsHelpersOptions(); optionsCallback(options); var helpers = new Dictionary <Category, IHelpers> { { Category.Regex, new RegexHelpers(handlebarsContext) }, { Category.Constants, new ConstantsHelpers(handlebarsContext) }, { Category.Enumerable, new EnumerableHelpers(handlebarsContext) }, { Category.Math, new MathHelpers(handlebarsContext) }, { Category.String, new StringHelpers(handlebarsContext) }, { Category.Url, new UrlHelpers(handlebarsContext) }, { Category.DateTime, new DateTimeHelpers(handlebarsContext, options.DateTimeService ?? new DateTimeService()) } }; var extra = new Dictionary <Category, string> { { Category.XPath, "XPathHelpers" }, { Category.Xeger, "XegerHelpers" }, { Category.Random, "RandomHelpers" }, { Category.JsonPath, "JsonPathHelpers" }, { Category.DynamicLinq, "DynamicLinqHelpers" }, { Category.Humanizer, "HumanizerHelpers" } }; var paths = options.CustomHelperPaths ?? new List <string> { Directory.GetCurrentDirectory() }; var extraHelpers = PluginLoader.Load(paths, extra, handlebarsContext); foreach (var item in extraHelpers) { helpers.Add(item.Key, item.Value); } // https://github.com/Handlebars-Net/Handlebars.Net#relaxedhelpernaming handlebarsContext.Configuration.Compatibility.RelaxedHelperNaming = options.PrefixSeparatorIsDot; foreach (var item in helpers.Where(h => options.Categories == null || options.Categories.Length == 0 || options.Categories.Contains(h.Key))) { RegisterCustomHelper(handlebarsContext, options, item.Key.ToString(), item.Value); } if (options.CustomHelpers is { })
public static void Register(IHandlebars handlebarsContext, IFileSystemHandler fileSystemHandler) { HandleBarsRegex.Register(handlebarsContext); HandleBarsJsonPath.Register(handlebarsContext); HandleBarsLinq.Register(handlebarsContext); HandleBarsRandom.Register(handlebarsContext); HandleBarsXeger.Register(handlebarsContext); HandleBarsXPath.Register(handlebarsContext); HandleBarsFile.Register(handlebarsContext, fileSystemHandler); }
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); } }
/// <summary> /// /// </summary> /// <param name="templateResolver"></param> /// <param name="viewSettings"></param> public TemplateService(ITemplateResolver templateResolver, ViewSettings viewSettings) { _templateResolver = templateResolver; _hbsService = Handlebars.Create(); RegisterHelpers(viewSettings); _templateResolver.GetAllPartialTemplates().ForEach(template => { try { _hbsService.RegisterTemplate(template.Key, template.Value); } catch (System.Exception ex) { throw new System.Exception($"Error at template key = {template.Key}", ex); } }); }
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; } } }); }
private static JToken ReplaceSingleNode(IHandlebars handlebarsContext, string stringValue, object context) { var templateForStringValue = handlebarsContext.Compile(stringValue); string transformedString = templateForStringValue(context); if (!string.Equals(stringValue, transformedString)) { const string property = "_"; JObject dummy = JObject.Parse($"{{ \"{property}\": null }}"); JToken node = dummy[property]; ReplaceNodeValue(node, transformedString); return(dummy[property]); } return(stringValue); }
public static Templates Load(string languageName, IHandlebars hb) { string templateDirectory = Path.GetFullPath(Path.Combine( BasePath, "Languages", languageName)); var templates = new Templates(); foreach (var file in Directory.EnumerateFiles(templateDirectory, "*.hb", SearchOption.AllDirectories)) { var relative = Path.GetFullPath(file); relative = relative.Substring(templateDirectory.Length + 1); relative = relative.Substring(0, relative.Length - 3); // Remove extension templates.Add(relative, new Template(LoadTemplateFile(hb, file))); } return(templates); }
public List <CodeFile> GenerateCode(ServiceClientModel model, GeneratorOptions options) { Language language = Language.Get(options.LanguageName); IHandlebars hb = Handlebars.Create(); RegisterHelpers(hb, language, options); Templates templates = language.GetTemplates(hb); RegisterTemplates(hb, templates); var context = new GenerateCodeContext(model, options, templates, language); language.GenerateCode(context); return(context.Files.Values.ToList()); }
public MainForm() { InitializeComponent(); _InventoryManager = new InventoryManager(); _MixModel = new MixModel(); var handlebarsConfig = new HandlebarsConfiguration(); handlebarsConfig.Helpers.Add("percent", (output, context, arguments) => output.Write(string.Format("{0:P}", arguments))); handlebarsConfig.Helpers.Add("unit", (output, context, arguments) => output.Write(string.Format("{0} {1}", arguments))); _Handlebars = Handlebars.Create(handlebarsConfig); tabPageEntryBindingSource.DataSource = new List <TabPageEntry> { new TabPageEntry(R.mix, R.TabMix), new TabPageEntry(R.recipes, R.TabRecipes), new TabPageEntry(R.ingredients, R.TabIngredients) }; _InventoryManager.PropertyChanged += OnInventoryManagerPropertyChanged; if (!string.IsNullOrEmpty(Settings.Default.LastInventoryFile)) { _InventoryManager.Load(Settings.Default.LastInventoryFile); } else { _InventoryManager.New("new_inventory.xml"); } numMixVolume.DataBindings.Add(nameof(NumericUpDown.Value), _MixModel, nameof(MixModel.Volume), false, DataSourceUpdateMode.OnPropertyChanged); numMixNicotine.DataBindings.Add(nameof(NumericUpDown.Value), _MixModel, nameof(MixModel.NicotineDose), false, DataSourceUpdateMode.OnPropertyChanged); numMixVg.DataBindings.Add(nameof(NumericUpDown.Value), _MixModel, nameof(MixModel.VgPercentage), false, DataSourceUpdateMode.OnPropertyChanged); numMixPg.DataBindings.Add(nameof(NumericUpDown.Value), _MixModel, nameof(MixModel.PgPercentage), false, DataSourceUpdateMode.OnPropertyChanged); _MixModel.PropertyChanged += OnMixModelPropertyChanged; mixIngredientModelBindingSource.DataSource = _MixModel.Ingredients; SetErrors(); cmbRecipeIngredientAdd.ComboBox.DataSource = ingredientBindingSource; SetTitle(); saveInventoryToolStripMenuItem.Enabled = _InventoryManager.IsDirty; }
public HandlebarsTemplateHandler( ISourceHandler sourceHandler, IHandlebars handlebars, IOptions <SiteConfig> siteConfig) { this.handlebars = handlebars; this.siteConfig = siteConfig.Value; using var sr = new StreamReader(sourceHandler.GetTemplate()); this.RegisterHelpers(); this.renderTemplate = this.handlebars.Compile(sr); this.RegisterPartials(sourceHandler.GetPartials()); this.RegisterLayouts(sourceHandler.GetLayouts()); }
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); } }); }
private void RegisterHelpers(IHandlebars hbs) { RegisterDivideHelper(hbs); RegisterMultiplyHelper(hbs); RegisterAdditionHelper(hbs); RegisterSubstractionHelper(hbs); RegisterEqualHelper(hbs); RegisterFormatNumberHelper(hbs); RegisterFormatDateTimeHelper(hbs); RegisterImageUrlHelper(hbs); RegisterArrayIndexHelper(hbs); RegisterArrayTranslateHelper(hbs); RegisterArrayLookupHelper(hbs); RegisterIfAndHelper(hbs); RegisterIfInHelper(hbs); RegisterEachPublishedHelper(hbs); RegisterConvertHtmlToTextHelper(hbs); RegisterTruncateWordsHelper(hbs); }
public static object Parse(IHandlebars context, string valueAsString) { if (int.TryParse(valueAsString, NumberStyles.Any, context.Configuration.FormatProvider, out int valueAsInt)) { return(valueAsInt); } if (long.TryParse(valueAsString, NumberStyles.Any, context.Configuration.FormatProvider, out long valueAsLong)) { return(valueAsLong); } if (double.TryParse(valueAsString, NumberStyles.Any, context.Configuration.FormatProvider, out double valueAsDouble)) { return(valueAsDouble); } return(valueAsString); }
public static void Register(IHandlebars handlebarsContext, IFileSystemHandler fileSystemHandler) { // Register https://github.com/StefH/Handlebars.Net.Helpers HandlebarsHelpers.Register(handlebarsContext); // Register WireMock.Net specific helpers HandlebarsRegex.Register(handlebarsContext); HandlebarsJsonPath.Register(handlebarsContext); HandlebarsLinq.Register(handlebarsContext); HandlebarsRandom.Register(handlebarsContext); HandlebarsXeger.Register(handlebarsContext); HandlebarsXPath.Register(handlebarsContext); HandlebarsFile.Register(handlebarsContext, fileSystemHandler); }
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); }
public static void Register(IHandlebars handlebarsContext, IFileSystemHandler fileSystemHandler) { // Register https://github.com/StefH/Handlebars.Net.Helpers HandlebarsHelpers.Register(handlebarsContext, o => { o.CustomHelperPaths = new string[] { Directory.GetCurrentDirectory() #if !NETSTANDARD1_3 , Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) #endif } .Distinct() .ToList(); o.CustomHelpers = new Dictionary <string, IHelpers> { { "File", new FileHelpers(handlebarsContext, fileSystemHandler) } }; }); }
public static object?Parse(IHandlebars context, object?argument, bool convertObjectArrayToStringList = false) { switch (argument) { case UndefinedBindingResult valueAsUndefinedBindingResult: if (TryParseUndefinedBindingResult(valueAsUndefinedBindingResult, out List <object?>?parsedAsObjectList)) { if (convertObjectArrayToStringList) { return(parsedAsObjectList.Cast <string?>().ToList()); } return(parsedAsObjectList); } return(argument); default: return(argument); } }
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); } }); }
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); } }); }