1
+ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
2
+ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3
+
4
+ using System ;
5
+ using System . Linq ;
6
+ using Microsoft . AspNet . Hosting ;
7
+ using Microsoft . AspNet . Razor . Runtime . TagHelpers ;
8
+
9
+ namespace Microsoft . AspNet . Mvc . TagHelpers
10
+ {
11
+ /// <summary>
12
+ /// <see cref="ITagHelper"/> implementation targeting <environment> elements that conditionally renders content
13
+ /// based on the current value of <see cref="IHostingEnvironment.EnvironmentName"/>.
14
+ /// </summary>
15
+ public class EnvironmentTagHelper : TagHelper
16
+ {
17
+ private static readonly char [ ] _nameSeparator = new [ ] { ',' } ;
18
+
19
+ /// <summary>
20
+ /// A comma separated list of environment names in which the content should be rendered.
21
+ /// </summary>
22
+ public string Names { get ; set ; }
23
+
24
+ // Protected to ensure subclasses are correctly activated. Internal for ease of use when testing.
25
+ [ Activate ]
26
+ protected internal IHostingEnvironment HostingEnvironment { get ; set ; }
27
+
28
+ public override void Process ( TagHelperContext context , TagHelperOutput output )
29
+ {
30
+ // Always strip the outer tag name as we never want <environment> to render
31
+ output . TagName = null ;
32
+
33
+ if ( string . IsNullOrWhiteSpace ( Names ) )
34
+ {
35
+ // No names specified, do nothing
36
+ return ;
37
+ }
38
+
39
+ var environments = Names . Split ( _nameSeparator , StringSplitOptions . RemoveEmptyEntries ) ;
40
+
41
+ if ( environments . Length == 0 )
42
+ {
43
+ // No names specified, do nothing
44
+ return ;
45
+ }
46
+
47
+ var currentEnvironmentName = HostingEnvironment . EnvironmentName . Trim ( ) ;
48
+
49
+ if ( environments . Any ( name => string . Equals ( name . Trim ( ) , currentEnvironmentName , StringComparison . OrdinalIgnoreCase ) ) )
50
+ {
51
+ // Matching environment name found, do nothing
52
+ return ;
53
+ }
54
+
55
+ // No matching environment name found, supress all output
56
+ output . SupressOutput ( ) ;
57
+ }
58
+ }
59
+ }
0 commit comments