|
| 1 | +using Microsoft.AspNetCore.Mvc.Rendering; |
| 2 | +using Microsoft.AspNetCore.Mvc.ViewFeatures; |
| 3 | +using Microsoft.AspNetCore.Razor.TagHelpers; |
| 4 | +using Umbraco.Cms.Core.Models.PublishedContent; |
| 5 | +using Umbraco.Extensions; |
| 6 | + |
| 7 | +namespace Our.Umbraco.TagHelpers |
| 8 | +{ |
| 9 | + /// <summary> |
| 10 | + /// Fallback Umbraco properties |
| 11 | + /// </summary> |
| 12 | + [HtmlTargetElement("our-fallback")] |
| 13 | + public class OurFallbackTagHelper : TagHelper |
| 14 | + { |
| 15 | + /// <summary> |
| 16 | + /// The property on the Model to use as a fallback such as Model.Header |
| 17 | + /// Would just be Header |
| 18 | + /// </summary> |
| 19 | + [HtmlAttributeName("property")] |
| 20 | + public ModelExpression ModelProperty { get; set; } |
| 21 | + |
| 22 | + [HtmlAttributeName("mode")] |
| 23 | + public Fallback Mode { get; set; } |
| 24 | + |
| 25 | + /// <summary> |
| 26 | + /// If using the fallback mode as Language then you can specify the culture to fallback to |
| 27 | + /// </summary> |
| 28 | + [HtmlAttributeName("culture")] |
| 29 | + public string CultureCode { get; set; } = null; |
| 30 | + |
| 31 | + [HtmlAttributeNotBound] |
| 32 | + [ViewContext] |
| 33 | + public ViewContext ViewContext { get; set; } |
| 34 | + |
| 35 | + public override void Process(TagHelperContext context, TagHelperOutput output) |
| 36 | + { |
| 37 | + // Check to see that the Model Property is NOT a complex type or a collection of things |
| 38 | + var isComplexType = ModelProperty.ModelExplorer.Metadata.IsComplexType; |
| 39 | + var isEnumerableType = ModelProperty.ModelExplorer.Metadata.IsEnumerableType; |
| 40 | + |
| 41 | + // Only can support simpler things such as strings (as if collection) |
| 42 | + // We have no way of knowing how they want to iterate and display that HTML etc |
| 43 | + if(isComplexType || isEnumerableType) |
| 44 | + { |
| 45 | + output.SuppressOutput(); |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + // Attempt to fetch/cast the Model as IPublishedContent |
| 50 | + var contentNode = ViewContext.ViewData.Model as IPublishedContent; |
| 51 | + if(contentNode == null) |
| 52 | + { |
| 53 | + output.SuppressOutput(); |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + output.TagName = ""; // Remove the outer <our-fallback> |
| 58 | + |
| 59 | + // Get the Model property with fallback mode |
| 60 | + var result = contentNode.Value(ModelProperty.Name, fallback: Mode, culture: CultureCode); |
| 61 | + |
| 62 | + // If we have a value that can be |
| 63 | + if (string.IsNullOrWhiteSpace($"{result}") == false) |
| 64 | + { |
| 65 | + output.Content.SetHtmlContent($"{result}"); |
| 66 | + return; |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments