Document directory
- NVelocityViewEngine
- NVelocityView
- ExtensionDuck
In my blog post, there is a saying: "I have been wondering whether there is a way to separately restrict the access permissions of the Code in the View, similar to the trust level, this trust level is used to restrict the code in the template. ". John Geng, a reader, asked why he didn't quite understand how to use trust level to lock the view. My intention is to hope that in view, developers can only write code for some specific functions and call some specific open APIs. For most of the Code with relatively high security level, for example, Apis or class libraries such as reading and writing files cannot be used in views. This is very important for us to open the template and provide it to our users online for modification. Currently, no matter whether WebForm or Razor is a very free template, what the View can do is equivalent to the code written by the Controller or other places, so that the View cannot be opened for online modification by users.
In the same blog post, the reader johngeng mentioned that it prefers $ instead of @. Since I didn't know NVelocity before, I misunderstood that it was about the client Development Kit jquery. Now it seems that he is talking about NVelocity. Maybe he thinks this person cannot be taught, and he does not directly reply to my questions, which can only blame him for being too narrow in his knowledge.
If I have not recently added support for a multi-template engine for a project, I may never be able to answer the two questions above, and both answers are related to NVelocity. Although I have always seen the term NVelocity, I have never remembered it when I want to select a template engine other than WebForm, my colleague @ Longson reminded me that the NVelocity template engine is worth a try. After reading the official syntax introduction, I have to say that it is a very simple and practical template without losing its flexibility and security. The flexibility I refer to is that it is not as restrictive as StringTemplate, and even functions of an object are not allowed to be called. Security also satisfies the requirement that developers can only call specified APIs on the template. So far, NVelocity has made me very satisfied.
In ASP. net mvc switch view engine is very simple, in ASP. after the NET MVC1.0 came out, MvcContrib once provided a variety of view engine switching options, but in recent versions, I have never found the relevant code, the Code has been removed, but related topics have not been deleted in its introduction document. I also found the implementation he extracted from MvcContrib on the blog of @ chongdian kids shoes. However, this implementation is outdated compared with MVC3, and some interfaces have been changed or removed. For example, the IViewLocator interface does not exist. In addition, it removes the previously supported function of calling the HtmlHelper extension method, and the most important thing is to support extension functions, because I have customized some necessary extension methods. Next let's take a look at the details of several NVelocity for ASP. net mvc classes:
NVelocityViewEngine
In the previous implementation, the IViewEngine interface was directly implemented, and the View path is located by IViewLocator. In MVC2, the implementation of this part is modified. MVC provides the VirtualPathProviderViewEngine template method class. In the subclass, we need to set the path format to be searched, other events can be handed over to the template method class, which can simplify our implementation and be consistent with the default path search method.
At the same time, because I use the Nvelocity built-in relative file path to find the template and use the VirtualPath style, after finding VirtualPath, we need to convert it to the actual physical path, the template content is loaded directly through the physical path, while the built-in FileResourceLoader does not support loading templates from the physical path. Therefore, we need to implement the FileResourceLoader to support loading methods from the physical path. The code for these two classes is as follows:
public class FileResourceLoaderEx : FileResourceLoader{ public FileResourceLoaderEx() : base() { } private Stream FindTemplate(string filePath) { try { FileInfo file = new FileInfo(filePath); return new BufferedStream(file.OpenRead()); } catch (Exception exception) { base.runtimeServices.Debug(string.Format("FileResourceLoader : {0}", exception.Message)); return null; } } public override long GetLastModified(global::NVelocity.Runtime.Resource.Resource resource) { if (File.Exists(resource.Name)) { FileInfo file = new FileInfo(resource.Name); return file.LastWriteTime.Ticks; } return base.GetLastModified(resource); } public override Stream GetResourceStream(string templateName) { if (File.Exists(templateName)) { return FindTemplate(templateName); } return base.GetResourceStream(templateName); } public override bool IsSourceModified(global::NVelocity.Runtime.Resource.Resource resource) { if (File.Exists(resource.Name)) { FileInfo file = new FileInfo(resource.Name); return (!file.Exists || (file.LastWriteTime.Ticks != resource.LastModified)); } return base.IsSourceModified(resource); }}public class NVelocityViewEngine : VirtualPathProviderViewEngine, IViewEngine{ public static NVelocityViewEngine Default = null; private static readonly IDictionary DEFAULT_PROPERTIES = new Hashtable(); private readonly VelocityEngine _engine; static NVelocityViewEngine() { string targetViewFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "views"); //DEFAULT_PROPERTIES.Add(RuntimeConstants.RESOURCE_LOADER, "file"); DEFAULT_PROPERTIES.Add(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, targetViewFolder); DEFAULT_PROPERTIES.Add("file.resource.loader.class", "NVelocityEngine.FileResourceLoaderEx\\,NVelocityEngine"); Default = new NVelocityViewEngine(); } public NVelocityViewEngine() : this(DEFAULT_PROPERTIES) { } public NVelocityViewEngine(IDictionary properties) { base.MasterLocationFormats = new string[] { "~/Views/{1}/{0}.vm", "~/Views/Shared/{0}.vm" }; base.AreaMasterLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/{0}.vm", "~/Areas/{2}/Views/Shared/{0}.vm" }; base.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.vm", "~/Views/Shared/{0}.vm" }; base.AreaViewLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/{0}.vm", "~/Areas/{2}/Views/Shared/{0}.vm" }; base.PartialViewLocationFormats = base.ViewLocationFormats; base.AreaPartialViewLocationFormats = base.AreaViewLocationFormats; base.FileExtensions = new string[] { "vm" }; if (properties == null) properties = DEFAULT_PROPERTIES; ExtendedProperties props = new ExtendedProperties(); foreach (string key in properties.Keys) { props.AddProperty(key, properties[key]); } _engine = new VelocityEngine(); _engine.Init(props); } protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) { Template viewTemplate = GetTemplate(viewPath); Template masterTemplate = GetTemplate(masterPath); NVelocityView view = new NVelocityView(controllerContext, viewTemplate, masterTemplate); return view; } protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) { Template viewTemplate = GetTemplate(partialPath); NVelocityView view = new NVelocityView(controllerContext, viewTemplate, null); return view; } public Template GetTemplate(string viewPath) { if (string.IsNullOrEmpty(viewPath)) { return null; } return _engine.GetTemplate(System.Web.Hosting.HostingEnvironment.MapPath(viewPath)); } }NVelocityView
It mainly implements the IView interface and the Render method to combine the template with the current context and output it. This class is also implemented, and IViewDataContainer does not seem to be particularly necessary. NVelocity Render is also very simple, just plug the desired object into the context of the NVelocity execution, and then call the Merge method to OK. Note that in the NVelocity template, we can call any attributes and methods in the context object, but there is no way to call the extension methods on the object. At this time, we need to use the IDuck interface provided by NVelocity to support the extension method. The following code is: new HtmlExtensionDuck (context, this );. The complete code is as follows:
public class NVelocityView : IViewDataContainer, IView{ private ControllerContext _controllerContext; private readonly Template _masterTemplate; private readonly Template _viewTemplate; public NVelocityView(ControllerContext controllerContext, string viewPath, string masterPath) : this(controllerContext, NVelocityViewEngine.Default.GetTemplate(viewPath), NVelocityViewEngine.Default.GetTemplate(masterPath)) { } public NVelocityView(ControllerContext controllerContext, Template viewTemplate, Template masterTemplate) { _controllerContext = controllerContext; _viewTemplate = viewTemplate; _masterTemplate = masterTemplate; } public Template ViewTemplate { get { return _viewTemplate; } } public Template MasterTemplate { get { return _masterTemplate; } } private VelocityContext CreateContext(ViewContext context) { Hashtable entries = new Hashtable(StringComparer.InvariantCultureIgnoreCase); if (context.ViewData != null) { foreach (var pair in context.ViewData) { entries[pair.Key] = pair.Value; } } entries["viewdata"] = context.ViewData; entries["tempdata"] = context.TempData; entries["routedata"] = context.RouteData; entries["controller"] = context.Controller; entries["httpcontext"] = context.HttpContext; entries["viewbag"] = context.ViewData; CreateAndAddHelpers(entries, context); return new VelocityContext(entries); } private void CreateAndAddHelpers(Hashtable entries, ViewContext context) { entries["html"] = entries["htmlhelper"] = new HtmlExtensionDuck(context, this); entries["url"] = entries["urlhelper"] = new UrlHelper(context.RequestContext); entries["ajax"] = entries["ajaxhelper"] = new AjaxHelper(context, this); } public void Render(ViewContext viewContext, TextWriter writer) { this.ViewData = viewContext.ViewData; bool hasLayout = _masterTemplate != null; VelocityContext context = CreateContext(viewContext); if (hasLayout) { StringWriter sw = new StringWriter(); _viewTemplate.Merge(context, sw); context.Put("childContent", sw.GetStringBuilder().ToString()); _masterTemplate.Merge(context, writer); } else { _viewTemplate.Merge(context, writer); } } private ViewDataDictionary _viewData; public ViewDataDictionary ViewData { get { if (_viewData == null) { return _controllerContext.Controller.ViewData; } return _viewData; } set { _viewData = value; } }}ExtensionDuck
ExtensionDuck is the implementation of the IDuck interface. It is the base class of the Duck object that we need to provide extension method support. All objects that need to be attached to the extension method can simplify most of the work by inheriting this method:
public class ExtensionDuck : IDuck{ private readonly object _instance; private readonly Type _instanceType; private readonly Type[] _extensionTypes; private Introspector _introspector; public ExtensionDuck(object instance) : this(instance, Type.EmptyTypes) { } public ExtensionDuck(object instance, params Type[] extentionTypes) { if(instance == null) throw new ArgumentNullException("instance"); _instance = instance; _instanceType = _instance.GetType(); _extensionTypes = extentionTypes; } public Introspector Introspector { get { if(_introspector == null) { _introspector = RuntimeSingleton.Introspector; } return _introspector; } set { _introspector = value; } } public object GetInvoke(string propName) { throw new NotSupportedException(); } public void SetInvoke(string propName, object value) { throw new NotSupportedException(); } public object Invoke(string method, params object[] args) { if(string.IsNullOrEmpty(method)) return null; MethodInfo methodInfo = Introspector.GetMethod(_instanceType, method, args); if(methodInfo != null) { return methodInfo.Invoke(_instance, args); } object[] extensionArgs = new object[args.Length + 1]; extensionArgs[0] = _instance; Array.Copy(args, 0, extensionArgs, 1, args.Length); foreach(Type extensionType in _extensionTypes) { methodInfo = Introspector.GetMethod(extensionType, method, extensionArgs); if(methodInfo != null) { return methodInfo.Invoke(null, extensionArgs); } } return null; }}
Next, we can implement an HtmlExtensionDuck and specify which extension methods of HtmlHelper can be called in View, the extension method to be opened can provide the static Class Name of the Extension Method in HTML_EXTENSION_TYPES:
public class HtmlExtensionDuck : ExtensionDuck{ public static readonly Type[] HTML_EXTENSION_TYPES = new Type[] { typeof(DisplayExtensions), typeof(DisplayTextExtensions), typeof(EditorExtensions), typeof(FormExtensions), typeof(InputExtensions), typeof(LabelExtensions), typeof(LinkExtensions), typeof(MvcForm), typeof(PartialExtensions), typeof(RenderPartialExtensions), typeof(SelectExtensions), typeof(TextAreaExtensions), typeof(ValidationExtensions) }; public HtmlExtensionDuck(ViewContext viewContext, IViewDataContainer container) : this(new HtmlHelper(viewContext, container)) { } public HtmlExtensionDuck(HtmlHelper htmlHelper) : this(htmlHelper, HTML_EXTENSION_TYPES) { } public HtmlExtensionDuck(HtmlHelper htmlHelper, params Type[] extentionTypes) : base(htmlHelper, extentionTypes) { }}
The complete implementation of NVelocity for ASP. net mvc is accomplished by the above classes. Then, we can register it directly to the system. We do not need to rewrite any Conroller. We can directly register ViewEngine into MVC to use it, or support a program to support harmonious scenes where multiple view engines coexist. Put the simple registration code in the Global. asax file:
ViewEngines.Engines.Add(NVelocityViewEngine.Default);
For more information, see downloading attachments.
In conclusion, NVelocity is indeed a simple and practical template engine, especially its syntax is very concise, and its API scalability is quite strong. The basic syntax style of Razor should be based on its syntax style. Although I like NVelocity very much now, if it is not a special need in special circumstances, in a common ASP. net mvc program, I will still use Razor sideways. It is more free, because it is directly supported by C # compilation, so we can do anything, which is very important for many developers. Another thing that can't be ignored is its IDE support, especially the code prompts, which are indeed quite comfortable.