public override void Process(TagHelperContext context, TagHelperOutput output) { //if no scripts were added, suppress the contents if (!_httpContextAccessor.HttpContext.Items.ContainsKey(InlineScriptConcatenatorTagHelper.ViewDataKey)) { output.SuppressOutput(); return; } //Otherwise get all the scripts for the page var scripts = _httpContextAccessor.HttpContext.Items[InlineScriptConcatenatorTagHelper.ViewDataKey] as IDictionary<string, NamedScriptInfo>; if (null == scripts) { output.SuppressOutput(); return; } //Concatenate all of them and set them as the contents of this tag var allScripts = string.Join("\r\n", OrderedScripts(scripts.Values).Select(os => os.Script)); output.TagMode = TagMode.StartTagAndEndTag; //HACK:Need to figure out how to get rid of the script tags for the placeholder element allScripts = $"</script><!--Rendered Scripts Output START-->\r\n{allScripts}\r\n</script><!--Rendered Scripts Output END--><script>";//HACK:ugly var unminifiedContent = output.Content.SetHtmlContent(allScripts); Debug.WriteLine(unminifiedContent.GetContent()); //TODO:Impliment dynamic minification (Assuming that some scenarios will be sped up, and others slowed down. Leave choice to user) }
public override void Process(TagHelperContext context, TagHelperOutput output) { if (MakePretty.HasValue && !MakePretty.Value) { return; } if (output.TagName == null) { // Another tag helper e.g. TagHelperviewComponentTagHelper has suppressed the start and end tags. return; } string prettyStyle; if (PrettyTagStyles.TryGetValue(output.TagName, out prettyStyle)) { var style = Style ?? string.Empty; if (!string.IsNullOrEmpty(style)) { style += ";"; } output.Attributes["style"] = style + prettyStyle; } }
public override void Process(TagHelperContext context, TagHelperOutput output) { StringBuilder sb = new StringBuilder(); string menuUrl = _UrlHelper.Action(ActionName, ControllerName, new { Area = AreaName }); if (string.IsNullOrEmpty(menuUrl)) throw new InvalidOperationException(string.Format("Can not find URL for {0}.{1}", ControllerName, ActionName)); output.TagName = "li"; var a = new TagBuilder("a"); a.MergeAttribute("href", $"{menuUrl}"); a.MergeAttribute("title", MenuText); a.InnerHtml.Append(MenuText); var routeData = ViewContext.RouteData.Values; var currentController = routeData["controller"]; var currentAction = routeData["action"]; var currentArea = routeData.ContainsKey("area") ? routeData["area"] : string.Empty; if (string.Equals(ActionName, currentAction as string, StringComparison.OrdinalIgnoreCase) && string.Equals(ControllerName, currentController as string, StringComparison.OrdinalIgnoreCase) && string.Equals(AreaName, currentArea as string, StringComparison.OrdinalIgnoreCase)) { output.Attributes.Add("class", "active"); } output.Content.SetContent(a); }
public override void Process(TagHelperContext context, TagHelperOutput output) { var surroundingTagName = Surround.ToLowerInvariant(); output.PreElement.AppendHtml($"<{surroundingTagName}>"); output.PostElement.AppendHtml($"</{surroundingTagName}>"); }
public override void Process(TagHelperContext context, TagHelperOutput output) { if (ShowIfNull != null) { output.SuppressOutput(); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "div"; if (output.Attributes["class"].IsNull()) { output.Attributes["class"] = "item"; } else { output.Attributes["class"].Value += " item"; } /* <div class="item"> <i class="marker icon"></i> <div class="content">@Html.DisplayFor(x => item.FullAddress)</div> </div> */ var html = new StringBuilder(); html.Append($"<i class='{Icon} icon'></i>"); html.Append($"<div class='content'>{Content}</div>"); var childContent = output.GetChildContentAsync(); output.Content.SetHtmlContent(html.ToString()); }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { var request = this.contextAccessor.HttpContext.Request; var result = await Prerenderer.RenderToString( applicationBasePath: this.applicationBasePath, nodeServices: this.nodeServices, bootModule: new JavaScriptModuleExport(this.ModuleName) { exportName = this.ExportName, webpackConfig = this.WebpackConfigPath }, requestAbsoluteUrl: UriHelper.GetEncodedUrl(this.contextAccessor.HttpContext.Request), requestPathAndQuery: request.Path + request.QueryString.Value); output.Content.SetHtmlContent(result.Html); // Also attach any specified globals to the 'window' object. This is useful for transferring // general state between server and client. if (result.Globals != null) { var stringBuilder = new StringBuilder(); foreach (var property in result.Globals.Properties()) { stringBuilder.AppendFormat("window.{0} = {1};", property.Name, property.Value.ToString(Formatting.None)); } if (stringBuilder.Length > 0) { output.PostElement.SetHtmlContent($"<script>{ stringBuilder.ToString() }</script>"); } } }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { var localizer = Localizer ?? GetViewLocalizer(); var aspLocAttr = output.Attributes["asp-loc"]; if (aspLocAttr != null) { var resourceKey = aspLocAttr.Minimized ? (await output.GetChildContentAsync()).GetContent() : aspLocAttr.Value.ToString(); output.Content.SetContent(localizer.GetHtml(resourceKey)); output.Attributes.Remove(aspLocAttr); } var localizeAttributes = output.Attributes.Where(attr => attr.Name.StartsWith("asp-loc-", StringComparison.OrdinalIgnoreCase)).ToList(); foreach (var attribute in localizeAttributes) { var attributeToLocalize = output.Attributes[attribute.Name.Substring("asp-loc-".Length)]; if (attributeToLocalize != null) { var resourceKey = attribute.Minimized ? attributeToLocalize.Value.ToString() : attribute.Value.ToString(); attributeToLocalize.Value = localizer.GetHtml(resourceKey); } output.Attributes.Remove(attribute); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { var specified = context?.AllAttributes[ImagesAttributeName]?.Name == ImagesAttributeName && Images != null && Images.Any(); if (specified) { string classValue; classValue = output.Attributes.ContainsName("class") ? string.Format("{0} {1}", output.Attributes["class"], "lazyload") : "lazyload"; output.Attributes["class"] = classValue; var images = Images.ToList(); if (images.Count == 1) { output.Attributes.Add("data-src", images[0]?.Url); } else { output.Attributes.Add("data-sizes", "auto"); List<string> sizes = new List<string>(); foreach (var image in images) { sizes.Add(MakePath(image.Url, image.Width)); } output.Attributes.Add("data-srcset", string.Join(",", sizes)); } } else { base.Process(context, output); } }
public override async void Process(TagHelperContext context, TagHelperOutput output) { var originalContent = await output.GetChildContentAsync(); output.AppendClass("form-group"); TagBuilder labelBuilder = null; if (!originalContent.GetContent().Contains("<label")) { labelBuilder = FormGroupLabel.Get(Horizontal, LabelText); } var contentDiv = new TagBuilder("div"); if (Horizontal) { contentDiv.AddCssClass("col-sm-8"); } contentDiv.InnerHtml.AppendHtml(originalContent.GetContent()); output.TagName = "div"; output.Content.Clear(); if (labelBuilder != null) { output.Content.Append(labelBuilder); } output.Content.Append(contentDiv); base.Process(context, output); }
/// <inheritdoc /> public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } await output.GetChildContentAsync(); var formContext = ViewContext.FormContext; if (formContext.HasEndOfFormContent) { foreach (var content in formContext.EndOfFormContent) { output.PostContent.Append(content); } } // Reset the FormContext ViewContext.FormContext = null; }
public override void Process(TagHelperContext context, TagHelperOutput output) { TagBuilder table = new TagBuilder("table"); table.GenerateId(context.UniqueId, "id"); var attributes = context.AllAttributes.Where(a => a.Name != ItemsAttributeName).ToDictionary(a => a.Name); table.MergeAttributes(attributes); var tr = new TagBuilder("tr"); var heading = Items.First(); PropertyInfo[] properties = heading.GetType().GetProperties(); foreach (var prop in properties) { var th = new TagBuilder("th"); th.InnerHtml.Append(prop.Name); tr.InnerHtml.Append(th); } table.InnerHtml.Append(tr); foreach (var item in Items) { tr = new TagBuilder("tr"); foreach (var prop in properties) { var td = new TagBuilder("td"); td.InnerHtml.Append(prop.GetValue(item).ToString()); tr.InnerHtml.Append(td); } table.InnerHtml.Append(tr); } output.Content.Append(table.InnerHtml); }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { (HtmlHelper as ICanHasViewContext)?.Contextualize(ViewContext); var content = await output.GetChildContentAsync(); output.Content.SetContent(HtmlHelper.Hidden(Name, content.GetContent(HtmlEncoder))); }
public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "select"; output.TagMode = TagMode.StartTagAndEndTag; output.AppendClass("form-control"); var optionsList = new List<TagBuilder>(); if (Items == null) { Items = new List<SelectListItem>(); } foreach (var item in Items) { var option = new TagBuilder("option"); option.Attributes.Add("value", item.Value); option.InnerHtml.Append(item.Text); optionsList.Add(option); } optionsList.ForEach(o => { output.Content.Append(o); }); base.Process(context, output); }
/// <inheritdoc /> /// <remarks>Does nothing if <see cref="ValidationSummary"/> is <see cref="ValidationSummary.None"/>.</remarks> public override void Process(TagHelperContext context, TagHelperOutput output) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } if (ValidationSummary == ValidationSummary.None) { return; } var tagBuilder = Generator.GenerateValidationSummary( ViewContext, excludePropertyErrors: ValidationSummary == ValidationSummary.ModelOnly, message: null, headerTag: null, htmlAttributes: null); if (tagBuilder != null) { output.MergeAttributes(tagBuilder); output.PostContent.Append(tagBuilder.InnerHtml); } }
public override void Init(TagHelperContext context) { base.Init(context); FormGroupContext = context.GetFormGroupContext(); FormContext = context.GetFormContext(); Size = Size ?? FormContext?.ControlSize; }
/// <inheritdoc /> public override void Init(TagHelperContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } // Note null or empty For.Name is allowed because TemplateInfo.HtmlFieldPrefix may be sufficient. // IHtmlGenerator will enforce name requirements. if (For.Metadata == null) { throw new InvalidOperationException(Resources.FormatTagHelpers_NoProvidedMetadata( "<select>", ForAttributeName, nameof(IModelMetadataProvider), For.Name)); } // Base allowMultiple on the instance or declared type of the expression to avoid a // "SelectExpressionNotEnumerable" InvalidOperationException during generation. // Metadata.IsEnumerableType is similar but does not take runtime type into account. var realModelType = For.ModelExplorer.ModelType; _allowMultiple = typeof(string) != realModelType && typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(realModelType.GetTypeInfo()); _currentValues = Generator.GetCurrentValues( ViewContext, For.ModelExplorer, expression: For.Name, allowMultiple: _allowMultiple); // Whether or not (not being highly unlikely) we generate anything, could update contained <option/> // elements. Provide selected values for <option/> tag helpers. context.Items[typeof(SelectTagHelper)] = _currentValues; }
protected override void BootstrapProcess(TagHelperContext context, TagHelperOutput output) { if (PrevText == null) PrevText = Ressources.Previous; if (NextText == null) NextText = Ressources.Next; output.TagName = "nav"; var content = "<ul class=\"pager\"><li"; if (PrevDisabled && Stretch) content += " class=\"previous disabled\"><a>"; else if (PrevDisabled) content += " class=\"disabled\"><a>"; else if (Stretch) content += $" class=\"previous\"><a href=\"{PrevHref}\">"; else content += $"><a href=\"{PrevHref}\">"; if (!HideArrows) content += "<span aria-hidden=\"true\">←</span> "; content += PrevText + "</a></li><li"; if (NextDisabled && Stretch) content += " class=\"next disabled\"><a>"; else if (NextDisabled) content += " class=\"disabled\"><a>"; else if (Stretch) content += $" class=\"next\"><a href=\"{NextHref}\">"; else content += $"><a href=\"{NextHref}\">"; content += NextText; if (!HideArrows) content += " <span aria-hidden=\"true\">→</span>"; content += "</a></li></ul>"; output.Content.SetHtmlContent(content); }
protected override void BootstrapProcess(TagHelperContext context, TagHelperOutput output) { if (HiddenXs) output.AddCssClass("hidden-xs"); if (HiddenSm) output.AddCssClass("hidden-sm"); if (HiddenMd) output.AddCssClass("hidden-md"); if (HiddenLg) output.AddCssClass("hidden-lg"); if (HiddenPrint) output.AddCssClass("hidden-print"); if (SrOnly || SrOnlyFocusable) output.AddCssClass("sr-only"); if (SrOnlyFocusable) output.AddCssClass("sr-only-focusable"); if (VisibleXs != null) output.AddCssClass("visible-xs-" + VisibleXs.Value.GetDescription()); if (VisibleSm != null) output.AddCssClass("visible-sm-" + VisibleSm.Value.GetDescription()); if (VisibleMd != null) output.AddCssClass("visible-md-" + VisibleMd.Value.GetDescription()); if (VisibleLg != null) output.AddCssClass("visible-lg-" + VisibleLg.Value.GetDescription()); if (VisiblePrint != null) output.AddCssClass("visible-print-" + VisiblePrint.Value.GetDescription()); }
public void Process_ResolvesTildeSlashValues(object url, object expectedHref) { // Arrange var tagHelperOutput = new TagHelperOutput( tagName: "a", attributes: new TagHelperAttributeList { { "href", url } }, getChildContentAsync: _ => Task.FromResult<TagHelperContent>(null)); var urlHelperMock = new Mock<IUrlHelper>(); urlHelperMock .Setup(urlHelper => urlHelper.Content(It.IsAny<string>())) .Returns(new Func<string, string>(value => "/approot" + value.Substring(1))); var tagHelper = new UrlResolutionTagHelper(urlHelperMock.Object, new TestHtmlEncoder()); var context = new TagHelperContext( allAttributes: new ReadOnlyTagHelperAttributeList<IReadOnlyTagHelperAttribute>( Enumerable.Empty<IReadOnlyTagHelperAttribute>()), items: new Dictionary<object, object>(), uniqueId: "test"); // Act tagHelper.Process(context, tagHelperOutput); // Assert var attribute = Assert.Single(tagHelperOutput.Attributes); Assert.Equal("href", attribute.Name, StringComparer.Ordinal); Assert.IsType(expectedHref.GetType(), url); Assert.Equal(expectedHref.ToString(), attribute.Value.ToString()); Assert.False(attribute.Minimized); }
public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "select"; if (Disabled) { output.Attributes["disabled"] = "disabled"; } var items = new StringBuilder(); var cityList = DbContext.Cities.OrderBy(x => x.Name).ToList(); items.Append("<option value=\"\">Все города</option>"); foreach (var city in cityList) { if (city.Id == CityId) { items.Append($"<option value=\"{city.Id}\" selected=\"true\">{city.Name}</option>"); } else { items.Append($"<option value=\"{city.Id}\">{city.Name}</option>"); } } output.Content.SetHtmlContent(items.ToString()); output.Attributes.Add("class", "ui fluid dropdown"); }
/// <inheritdoc /> /// <remarks>Does nothing if <see cref="For"/> is <c>null</c>.</remarks> public override void Process(TagHelperContext context, TagHelperOutput output) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } var tagBuilder = Generator.GenerateTextArea( ViewContext, For.ModelExplorer, For.Name, rows: 0, columns: 0, htmlAttributes: null); if (tagBuilder != null) { // Overwrite current Content to ensure expression result round-trips correctly. output.Content.SetContent(tagBuilder.InnerHtml); output.MergeAttributes(tagBuilder); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { output.PostContent .AppendHtml("<footer>") .Append((string)ViewContext.ViewData["footer"]) .AppendHtml("</footer>"); }
/// <inheritdoc /> public override void Process(TagHelperContext context, TagHelperOutput output) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } output.CopyHtmlAttribute(SrcAttributeName, context); ProcessUrlAttribute(SrcAttributeName, output); if (AppendVersion) { EnsureFileVersionProvider(); // Retrieve the TagHelperOutput variation of the "src" attribute in case other TagHelpers in the // pipeline have touched the value. If the value is already encoded this ImageTagHelper may // not function properly. Src = output.Attributes[SrcAttributeName].Value as string; output.Attributes[SrcAttributeName] = _fileVersionProvider.AddFileVersionToPath(Src); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { if (HideIf) { output.SuppressOutput(); } }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { var childContent = await output.GetChildContentAsync(); var modalContext = (ModalContext)context.Items[typeof(ModalTagHelper)]; modalContext.Body = childContent; output.SuppressOutput(); }
public override void Init(TagHelperContext context) { base.Init(context); FormGroupContext = context.GetFormGroupContext(); FormContext = context.GetFormContext(); if (FormGroupContext != null) { var formGroupContextClone = FormGroupContext.Clone(); context.SetFormGroupContext(formGroupContextClone); formGroupContextClone.ControlSize=BootstrapTagHelpers.Size.Default; if (FormGroupContext.FormContext != null) { formGroupContextClone.FormContext.ControlSize=BootstrapTagHelpers.Size.Default; context.SetFormContext(formGroupContextClone.FormContext); } } else if (FormContext != null) { FormTagHelper formTagHelperClone = FormContext.Clone(); context.SetFormContext(formTagHelperClone); formTagHelperClone.ControlSize=BootstrapTagHelpers.Size.Default; } if (Size == null) { var size = FormGroupContext?.ControlSize ?? FormContext?.ControlSize; if (size != null) Size = size == BootstrapTagHelpers.Size.Large ? SimpleSize.Large : SimpleSize.Small; } }
public override void Process(TagHelperContext context, TagHelperOutput output) { //set the tag name to a select...the attributes will carry along automatically. Otherwise grab context.AllAttributes output.TagName = "select"; using (var writer = new StringWriter()) { //loop through the items foreach (var item in SelectItems) { //create the option var option = new TagBuilder("option"); //set the value option.MergeAttribute("value", item.Value); //set the text option.InnerHtml.Append(item.Text); //write it to the writer option.WriteTo(writer, encoder); } //now output the writer to the page output.Content.SetHtmlContent(writer.ToString()); } }
/// <inheritdoc /> public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } await output.GetChildContentAsync(); var formContext = ViewContext.FormContext; if (formContext.HasEndOfFormContent) { // Perf: Avoid allocating enumerator for (var i = 0; i < formContext.EndOfFormContent.Count; i++) { output.PostContent.AppendHtml(formContext.EndOfFormContent[i]); } } // Reset the FormContext ViewContext.FormContext = null; }
public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "p"; output.Attributes["class"] = "example"; output.PostContent.SetContent("Hello from the tag helper! "); output.PostContent.Append("Title sent in was: " + Title + " and Body: " + Body); }