forked from Adolfi/UmbracoNineDemoSite
-
Notifications
You must be signed in to change notification settings - Fork 1
/
SiteVariableService.cs
49 lines (43 loc) · 1.63 KB
/
SiteVariableService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Cms.Web.Common;
using Umbraco.Extensions;
using UmbracoNineDemoSite.Core.Features.Shared.Constants;
namespace UmbracoNineDemoSite.Core.Features.Shared.Variables
{
public class SiteVariableService : ISiteVariable
{
private readonly UmbracoHelper umbracoHelper;
private Dictionary<string, object> variables;
public SiteVariableService(UmbracoHelper umbracoHelper)
{
this.umbracoHelper = umbracoHelper;
this.CollectVariables();
}
private void CollectVariables()
{
this.variables = new Dictionary<string, object>();
var home = this.umbracoHelper?.ContentAtRoot().FirstOrDefault(x => x.ContentType.Alias == ContentTypeAlias.Home);
var settings = home?.Children?.FirstOrDefault(x => x.ContentType.Alias == ContentTypeAlias.SiteSettings);
var siteVariables = settings?.Children.FirstOrDefault(x => x.ContentType.Alias == ContentTypeAlias.SiteVariables)?.Children;
if (siteVariables == null) return;
foreach (var variable in siteVariables)
{
variables.Add(variable.Value<string>("alias"), variable.Value("value"));
}
}
public T Get<T>(string alias, T fallback)
{
try
{
var variable = this.variables.TryGetValue(alias, out var value);
return (T)Convert.ChangeType(value, typeof(T));
}
catch (System.Exception)
{
return fallback;
}
}
}
}