Skip to content

Commit 967d501

Browse files
author
Warren Buckley
committed
Adds <our-fallback>
From last weeks Umbraco Discord MOB programming Hacktoberfest session
1 parent f2c19af commit 967d501

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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+
/// Use to fallback simple properties
11+
/// </summary>
12+
[HtmlTargetElement("our-fallback")]
13+
public class OurFallbackTagHelper : TagHelper
14+
{
15+
[HtmlAttributeName("property")]
16+
public ModelExpression ModelProperty { get; set; }
17+
18+
[HtmlAttributeName("mode")]
19+
public Fallback Mode { get; set; }
20+
21+
[HtmlAttributeName("culture")]
22+
public string CultureCode { get; set; } = null;
23+
24+
[HtmlAttributeNotBound]
25+
[ViewContext]
26+
public ViewContext ViewContext { get; set; }
27+
28+
public override void Process(TagHelperContext context, TagHelperOutput output)
29+
{
30+
// Check to see that the Model Property is NOT a complex type or a collection of things
31+
var isComplexType = ModelProperty.ModelExplorer.Metadata.IsComplexType;
32+
var isEnumerableType = ModelProperty.ModelExplorer.Metadata.IsEnumerableType;
33+
34+
// Only can support simpler things such as strings (as if collection)
35+
// We have no way of knowing how they want to iterate and display that HTML etc
36+
if(isComplexType || isEnumerableType)
37+
{
38+
output.SuppressOutput();
39+
return;
40+
}
41+
42+
// Attempt to fetch/cast the Model as IPublishedContent
43+
var contentNode = ViewContext.ViewData.Model as IPublishedContent;
44+
if(contentNode == null)
45+
{
46+
output.SuppressOutput();
47+
return;
48+
}
49+
50+
output.TagName = ""; // Remove the outer <our-fallback>
51+
52+
// Get the Model property with fallback mode
53+
var result = contentNode.Value(ModelProperty.Name, fallback: Mode, culture: CultureCode);
54+
55+
// If we have a value that can be
56+
if (string.IsNullOrWhiteSpace($"{result}") == false)
57+
{
58+
output.Content.SetHtmlContent($"{result}");
59+
return;
60+
}
61+
}
62+
}
63+
}

0 commit comments

Comments
 (0)