-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathViewScriptTagHelper.cs
executable file
·64 lines (53 loc) · 2.09 KB
/
ViewScriptTagHelper.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace nugsnet6;
public class ViewScriptTagHelper : TagHelper
{
private readonly IWebHostEnvironment environment;
private readonly IFileVersionProvider fileVersionProvider;
private const string AppendVersionAttributeName = "append-version";
public ViewScriptTagHelper(
IWebHostEnvironment environment,
IFileVersionProvider fileVersionProvider
)
{
this.environment = environment;
this.fileVersionProvider = fileVersionProvider;
}
[ViewContext]
public ViewContext? ViewContext { get; set; }
/// <summary>
/// Value indicating if file version should be appended to src urls.
/// </summary>
/// <remarks>
/// A query string "v" with the encoded content of the file is added.
/// </remarks>
[HtmlAttributeName(AppendVersionAttributeName)]
public bool? AppendVersion { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
// remove the `page-script` tag if script doesn't exist
output.TagName = null;
output.TagMode = TagMode.StartTagAndEndTag;
var viewPath = ViewContext?.View.Path;
var src = $"{viewPath}.js";
/* When the app is published, the framework automatically moves the script to the web root.
So we should check both places, with the content root first for development */
var fileInfo =
environment.ContentRootFileProvider.GetFileInfo(src)
?? environment.WebRootFileProvider.GetFileInfo(src);
if (fileInfo is { Exists: true })
{
// switch it to script now
output.TagName = "script";
output.Content = new DefaultTagHelperContent();
if (AppendVersion == true)
{
// people love their cache busting versions
src = fileVersionProvider.AddFileVersionToPath(src, src);
}
output.Attributes.Add("src", src);
}
}
}