private string GetBlobName() { var blobName = _configuration.GetValue <string>("OrchardCore.DataProtection.Azure:BlobName"); if (String.IsNullOrEmpty(blobName)) { blobName = $"{_shellOptions.ShellsContainerName}/{_shellSettings.Name}/DataProtectionKeys.xml"; } else { try { // Use Fluid directly as the service provider has not been built. var templateContext = new TemplateContext(); templateContext.MemberAccessStrategy.Register <ShellSettings>(); templateContext.SetValue("ShellSettings", _shellSettings); var template = FluidTemplate.Parse(blobName); blobName = template.Render(templateContext, NullEncoder.Default); blobName.Replace("\r", String.Empty).Replace("\n", String.Empty); } catch (Exception e) { _logger.LogCritical(e, "Unable to parse data protection blob name."); throw e; } } return(blobName); }
public string GenerateFluid <T>(string fluid, T model, string modelName = "Model", CultureInfo cultureInfo = null, bool registerType = false) where T : class { var template = FluidTemplate.Parse(fluid); var context = new TemplateContext(); if (cultureInfo != null) { context.CultureInfo = cultureInfo; } else { context.CultureInfo = CultureInfo.CurrentCulture; } if (registerType) { context.MemberAccessStrategy.Register <T>(); } context.SetValue(modelName, model); return(template.Render(context)); }
public async Task <string> RenderTemplateForModel <K>(string liquidTemplatePath, K model) { //Put some caching mechanism here. var path = Path.Combine(_webHostEnvironment.ContentRootPath, "Pages", liquidTemplatePath); var template = FluidTemplate.Parse(await File.ReadAllTextAsync(path)); return(await template.RenderAsync(new TemplateContext(model).SetValue(typeof(K).Name, model))); }
public void renders_empty_string_if_data_directory_does_not_exist() { var template = FluidTemplate.Parse(@"{{ data.people }}"); var templateContext = CreateTemplateContext(); var result = template.Render(templateContext); Assert.Equal("", result.Trim()); }
public bool EvalExpression(string expression, TemplateContext context, ContentData contentData = null) { context = PopulateContextFromContentData(context, contentData); var matchString = "TRUE"; var showIf = string.Concat("{% if ", expression, " %}", matchString, "{% endif %}"); var showIfTemplate = FluidTemplate.Parse(showIf); return(showIfTemplate.Render(context) == matchString); }
/// <summary> /// Parses the specified template to render. /// </summary> /// <param name="template">The template to parse and render.</param> public void Parse(string template) { if (template == null) { throw new ArgumentNullException(nameof(template)); } this.Template = template; this.fluidTemplate = FluidTemplate.Parse(this.Template); }
public void renders_nested_lists(string ext, string fileContent) { fileSystem.AddFile(Path.Combine(dataDirectory, $"members.{ext}"), new MockFileData(fileContent)); var template = FluidTemplate.Parse(@"{{ data.members | size }}"); var templateContext = CreateTemplateContext(); var result = template.Render(templateContext); Assert.Equal("3", result.Trim()); }
public void renders_deep_nested_object(string ext, string fileContent) { fileSystem.AddFile(Path.Combine(dataDirectory, $"person.{ext}"), new MockFileData(fileContent)); var template = FluidTemplate.Parse(@"{{ data.person.address.postalcode }}"); var templateContext = CreateTemplateContext(); var result = template.Render(templateContext); Assert.Equal("1234", result.Trim()); }
public void renders_nested_folder_object(string ext, string fileContent) { fileSystem.AddFile(Path.Combine(dataDirectory, $@"users\person.{ext}"), new MockFileData(fileContent)); var template = FluidTemplate.Parse(@"{{ data.users.person.name }}"); var templateContext = CreateTemplateContext(); var result = template.Render(templateContext); Assert.Equal("Eric Mill", result.Trim()); }
//TODO: This is currently not supported. See https://jekyllrb.com/docs/datafiles/#example-accessing-a-specific-author // [InlineData("csv", @"dave.name,dave.twitter //""David Smith"",""DavidSilvaSmith""")] // [InlineData("tsv", @"dave.name dave.twitter //""David Smith"" ""DavidSilvaSmith""")] public void renders_dictionary_accessors(string ext, string fileContent) { fileSystem.AddFile(Path.Combine(dataDirectory, $"people.{ext}"), new MockFileData(fileContent)); var template = FluidTemplate.Parse(@"{{ data.people['dave'].name }}"); var templateContext = CreateTemplateContext(); var result = template.Render(templateContext); Assert.Equal("David Smith", result.Trim()); }
public static async Task <IActionResult> GetOrchestrationTabMarkupFunction( // Using /a/p/i route prefix, to let Functions Host distinguish api methods from statics [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "a/p/i/orchestrations('{instanceId}')/custom-tab-markup('{templateName}')")] HttpRequest req, string instanceId, string templateName, [DurableClient(TaskHub = "%DFM_HUB_NAME%")] IDurableClient durableClient, ILogger log) { // Checking that the call is authenticated properly try { await Auth.ValidateIdentityAsync(req.HttpContext.User, req.Headers); } catch (Exception ex) { log.LogError(ex, "Failed to authenticate request"); return(new UnauthorizedResult()); } var status = await GetInstanceStatus(instanceId, durableClient, log); if (status == null) { return(new NotFoundObjectResult($"Instance {instanceId} doesn't exist")); } // The underlying Task never throws, so it's OK. var templatesMap = DetailedOrchestrationStatus.TabTemplatesTask.Result; string templateCode = templatesMap.GetTemplate(status.GetEntityTypeName(), templateName); if (templateCode == null) { return(new NotFoundObjectResult("The specified template doesn't exist")); } try { var fluidTemplate = FluidTemplate.Parse(templateCode); var fluidContext = new TemplateContext(status); return(new ContentResult() { Content = fluidTemplate.Render(fluidContext), ContentType = "text/html; charset=UTF-8" }); } catch (Exception ex) { return(new BadRequestObjectResult(ex.Message)); } }
public string Render(string input, TemplateContext context, ContentData contentData = null) { if (!IsTemplate(input)) { // Has no templating code... return(input); } context = PopulateContextFromContentData(context, contentData); var template = FluidTemplate.Parse(input); return(template.Render(context)); }
private void ParseBasePath(MediaS3StorageOptions options, TemplateContext templateContext) { try { var template = FluidTemplate.Parse(options.S3BasePath); options.S3BasePath = template.Render(templateContext, NullEncoder.Default); options.S3BasePath = options.S3BasePath.Replace("\r", String.Empty).Replace("\n", String.Empty); } catch (Exception e) { _logger.LogCritical(e, "Unable to parse Azure Media Storage base path."); throw; } }
private void ParseContainerName(MediaBlobStorageOptions options, TemplateContext templateContext) { // Use Fluid directly as this is transient and cannot invoke _liquidTemplateManager. try { var template = FluidTemplate.Parse(options.ContainerName); options.ContainerName = template.Render(templateContext, NullEncoder.Default); options.ContainerName.Replace("\r", String.Empty).Replace("\n", String.Empty); } catch (Exception e) { _logger.LogCritical(e, "Unable to parse Azure Media Storage container name."); throw e; } }
public void caches_result(string ext, string fileContent) { fileSystem.Directory.CreateDirectory(dataDirectory); var fileName = Path.Combine(dataDirectory, $"person.{ext}"); fileSystem.AddFile(fileName, new MockFileData(fileContent)); var template = FluidTemplate.Parse(@"{{ data.person.name }} {{ data.person.email }}"); var templateContext = CreateTemplateContext(); var result = template.Render(templateContext); Assert.Equal("Eric Mill [email protected]", result.Trim()); }
private void ParseContainerName(MediaS3StorageOptions options, TemplateContext templateContext) { // Use Fluid directly as this is transient and cannot invoke _liquidTemplateManager. try { var template = FluidTemplate.Parse(options.S3BucketName); // container name must be lowercase options.S3BucketName = template.Render(templateContext, NullEncoder.Default).ToLower(); options.S3BucketName = options.S3BucketName.Replace("\r", string.Empty).Replace("\n", string.Empty); } catch (Exception e) { _logger.LogCritical(e, "Unable to parse S3 Bucket name."); throw; } }
public void renders_multiple_files_with_nested_objects() { fileSystem.AddFile(Path.Combine(dataDirectory, $"eric.yml"), new MockFileData(@"name: Eric Mill")); fileSystem.AddFile(Path.Combine(dataDirectory, $"manuel.yml"), new MockFileData(@"name: Manuel Grundner")); var templateContext = CreateTemplateContext(); var templateEric = FluidTemplate.Parse(@"{{ data.eric.name }}"); var resultEric = templateEric.Render(templateContext); Assert.Equal("Eric Mill", resultEric.Trim()); var templateManuel = FluidTemplate.Parse(@"{{ data.manuel.name }}"); var resultManuel = templateManuel.Render(templateContext); Assert.Equal("Manuel Grundner", resultManuel.Trim()); }
private CloudBlobContainer GetBlobContainer(string connectionString) { var containerName = _configuration.GetValue <string>("OrchardCore.DataProtection.Azure:ContainerName") ?? "dataprotection"; // Use Fluid directly as the service provider has not been built. try { var templateContext = new TemplateContext(); templateContext.MemberAccessStrategy.Register <ShellSettings>(); templateContext.SetValue("ShellSettings", _shellSettings); var template = FluidTemplate.Parse(containerName); containerName = template.Render(templateContext, NullEncoder.Default); containerName.Replace("\r", String.Empty).Replace("\n", String.Empty); } catch (Exception e) { _logger.LogCritical(e, "Unable to parse data protection connection string."); throw e; } try { var storageAccount = CloudStorageAccount.Parse(connectionString); var blobClient = storageAccount.CreateCloudBlobClient(); var blobContainer = blobClient.GetContainerReference(containerName); var createContainer = _configuration.GetValue("OrchardCore.DataProtection.Azure:CreateContainer", true); if (createContainer) { _logger.LogDebug("Testing data protection container {ContainerName} existence", containerName); var result = blobContainer.CreateIfNotExistsAsync(BlobContainerPublicAccessType.Off, new BlobRequestOptions(), new OperationContext()).GetAwaiter().GetResult(); _logger.LogDebug("Data protection container {ContainerName} created: {Result}.", containerName, result); } return(blobContainer); } catch (Exception) { _logger.LogCritical("Unable to connect to Azure Storage to configure data protection storage. Ensure that an application setting containing a valid Azure Storage connection string is available at `Modules:OrchardCore.DataProtection.Azure:ConnectionString`."); throw; } }
protected override string RenderTemplate(string content, PageContext pageData) { // Replace all em HTML tags in liquid tags ({{ or {%) by underscores content = emHtmlRegex.Replace(content, "_"); var data = CreatePageData(pageData); var includes = Path.Combine(contextDrop.context.SourceFolder, "_includes"); includes = Path.GetFullPath(includes); data.FileProvider = new PretzelPhysicalFileProvider(new FileSystemPhysicalFileProvider(FileSystem, includes)); var template = FluidTemplate.Parse(content); var output = template.Render(data); return(output); }
public string Render <T>(string template, T model) { var fluidTemplate = FluidTemplate.Parse(template); var context = new TemplateContext(); context.MemberAccessStrategy = new UnsafeMemberAccessStrategy() { IgnoreCasing = true }; context.MemberAccessStrategy.Register(model.GetType()); // Allows any public property of the model to be used foreach (var property in model.GetType().GetProperties()) { context.SetValue(property.Name, property.GetValue(model)); } return(fluidTemplate.Render(context)); }
private string GetBlobContainerName(string connectionString) { var containerName = _configuration.GetValue("OrchardCore_DataProtection_Azure:ContainerName", "dataprotection"); // Use Fluid directly as the service provider has not been built. try { var templateContext = new TemplateContext(); templateContext.MemberAccessStrategy.Register <ShellSettings>(); templateContext.SetValue("ShellSettings", _shellSettings); var template = FluidTemplate.Parse(containerName); // container name must be lowercase containerName = template.Render(templateContext, NullEncoder.Default).ToLower(); containerName.Replace("\r", String.Empty).Replace("\n", String.Empty); } catch (Exception e) { _logger.LogCritical(e, "Unable to parse data protection connection string."); throw e; } var createContainer = _configuration.GetValue("OrchardCore_DataProtection_Azure:CreateContainer", true); if (createContainer) { try { _logger.LogDebug("Testing data protection container {ContainerName} existence", containerName); var _blobContainer = new BlobContainerClient(connectionString, containerName); var response = _blobContainer.CreateIfNotExistsAsync(PublicAccessType.None).GetAwaiter().GetResult(); _logger.LogDebug("Data protection container {ContainerName} created.", containerName); } catch (Exception) { _logger.LogCritical("Unable to connect to Azure Storage to configure data protection storage. Ensure that an application setting containing a valid Azure Storage connection string is available at `Modules:OrchardCore.DataProtection.Azure:ConnectionString`."); throw; } } return(containerName); }
static Templates() { var assembly = Assembly.GetExecutingAssembly(); var templateResourceNames = assembly .GetManifestResourceNames() .Where(name => name.StartsWith(s_TemplateResourcePrefix) && name.EndsWith(s_TemplateResourceSuffix)); foreach (var resourceName in templateResourceNames) { var templateName = resourceName .Replace(s_TemplateResourcePrefix, "") .Replace(s_TemplateResourceSuffix, ""); s_Templates.Add(templateName, new Lazy <FluidTemplate>(() => { var templateSource = EmbeddedResource.Load(resourceName); return(FluidTemplate.Parse(templateSource)); })); } }
public void ShouldThrowParseExceptionMissingTag(string template) { Assert.Throws <ParseException>(() => FluidTemplate.Parse(template)); }