1+ using Microsoft . AspNetCore . Mvc . ViewFeatures ;
2+ using Microsoft . AspNetCore . Razor . TagHelpers ;
3+ using System ;
4+ using System . Text ;
5+ using System . Threading . Tasks ;
6+
7+ namespace Serilog . Ui . Web
8+ {
9+ [ HtmlTargetElement ( "truncate" ) ]
10+ public class TruncateTagHelper : TagHelper
11+ {
12+ [ HtmlAttributeName ( "length" ) ]
13+ public int Length { get ; set ; }
14+
15+ [ HtmlAttributeName ( "truncate" ) ]
16+ public ModelExpression Truncate { get ; set ; }
17+
18+ public override async Task ProcessAsync ( TagHelperContext context , TagHelperOutput output )
19+ {
20+ if ( context == null )
21+ throw new ArgumentNullException ( nameof ( context ) ) ;
22+
23+ if ( output == null )
24+ throw new ArgumentNullException ( nameof ( output ) ) ;
25+
26+ await base . ProcessAsync ( context , output ) ;
27+
28+ string content = null ;
29+ if ( Truncate != null )
30+ content = Truncate . Model ? . ToString ( ) ;
31+
32+ content ??= ( await output . GetChildContentAsync ( NullHtmlEncoder . Default ) ) . GetContent ( NullHtmlEncoder . Default ) ;
33+
34+ if ( string . IsNullOrEmpty ( content ) )
35+ return ;
36+
37+ if ( content . Length <= Length )
38+ {
39+ output . Content . SetContent ( content ) ;
40+ return ;
41+ }
42+
43+ var sb = new StringBuilder ( ) ;
44+ sb . Append ( "<a href=\" #\" title=\" Click to view\" class=\" modal-trigger\" data-type=\" text\" >" ) ;
45+ sb . Append ( content . Substring ( 0 , Length ) ) ;
46+ sb . Append ( " ..." ) ;
47+ sb . Append ( "<span style=\" display: none\" >" ) ;
48+ sb . Append ( content ) ;
49+ sb . Append ( "</span></a>" ) ;
50+ output . Content . SetHtmlContent ( sb . ToString ( ) ) ;
51+ }
52+ }
53+ }
0 commit comments