예제 #1
0
        /// <summary>
        /// 使用RazorEngine编译cshtml页面.返回静态内容
        /// </summary>
        /// <param name="temps">temps是一个以路径为键,cshtml文件内容为值的字典.它包含了一个要被编译的cshtml主文件以及其引用的1个母板页和0~多个片段页.</param>
        /// <param name="mainCshtmlKey">要编译的主cshtml模板文件在temps中的key</param>
        /// <returns></returns>
        private static string RazorRun(Dictionary <string, string> temps, string mainCshtmlKey, object model = null)
        {
            // 添加要编译的cshtml文件,包括其引用的母板页和片段页
            foreach (string key in temps.Keys)
            {
                // 如果文件有变化才重新添加模板和编译,因为编译时间比较长
                if (!RazorCacheHelpers.IsChange(key, temps[key]))
                {
                    continue;
                }

                // 键是文件的相对路径名,是固定的,每个cshtml的路径是唯一的.
                ITemplateKey k = serveice.GetKey(key);

                // 先删除这个键,再添加之.由于键固定,不删除的话,会报键重复.
                ((DelegateTemplateManager)config.TemplateManager).RemoveDynamic(k);

                // 添加模板,以键为模板名,以cshtml内容为模板内容
                serveice.AddTemplate(k, temps[key]);

                // 编译之.由于键固定,如果不编译的话,就会使用上一次编译后的缓存(与这固定键对应的缓存).所以添加模板后,一定要重新编译.
                serveice.Compile(k);
            }
            // MainCshtmlKey是cshtml主页面,生成html时,必须以主cshtml模板的名.
            if (model == null)
            {
                return(serveice.Run(serveice.GetKey(mainCshtmlKey)));
            }
            return(serveice.Run(serveice.GetKey(mainCshtmlKey), null, model));
        }
        /// <summary>
        /// Adds and compiles a new template using the specified <paramref name="templateSource"/> and returns a <see cref="TemplateRunner{TModel}"/>.
        /// </summary>
        /// <typeparam name="TModel">The model type</typeparam>
        /// <param name="service"></param>
        /// <param name="templateSource"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static ITemplateRunner <TModel> CompileRunner <TModel>(this IRazorEngineService service, string templateSource, string name)
        {
            var key = service.GetKey(name);

            service.AddTemplate(key, templateSource);
            service.Compile(key, typeof(TModel));

            return(new TemplateRunner <TModel>(service, key));
        }
 public virtual string CreateEmail <T>(string templateName, T model)
 {
     try
     {
         var key = _service.GetKey(templateName);
         return(_service.RunCompile(key, typeof(T), model));
     }
     finally
     {
         _service.Dispose();
     }
 }
예제 #4
0
        /// <summary>
        /// 渲染数据
        /// </summary>
        /// <param name="key">缓存键</param>
        /// <param name="template">模板</param>
        /// <param name="model">数据模型</param>
        /// <param name="tp">模板类型</param>
        /// <returns>返回渲染后的字符串</returns>
        public string Format(string key, string template, object model = null, Type tp = null)
        {
            var ret = "";

            try
            {
                var          keyString = key.Replace(Cache.runPath, "");
                ITemplateKey km        = razor.GetKey(keyString);
                var          bl        = razor.IsTemplateCached(km, tp);
                if (bl)
                {
                    ret = razor.Run(km, tp, model, ViewBag);
                }
                else
                {
                    ret = razor.RunCompile(template, km, tp, model, ViewBag);
                }
            }
            catch (Exception ex)
            {
                Ex = ex.ToString();
            }
            return(ret);
        }
예제 #5
0
        public string Render(string key, Type modelType, object model)
        {
            TemplateState templateState;

            if (!_TemplateStates.TryGetValue(key, out templateState))
            {
                throw new ApplicationException("Unable to find template in cache");
            }
            var    cacheFileInfo = templateState.FileInfo;
            string templatePath  = cacheFileInfo.FullName;
            var    fileInfo      = new FileInfo(templatePath);

            if (!templateState.Compiled || fileInfo.LastWriteTimeUtc > cacheFileInfo.LastWriteTimeUtc)
            {
                try
                {
                    Console.WriteLine("Recompiling {0}", templatePath);
                    string source      = File.ReadAllText(templatePath);
                    var    templateKey = _Engine.GetKey(key);
                    _TemplateManager.RemoveDynamic(templateKey);
                    _CachingProvider.InvalidateCache(templateKey);
                    _Engine.Compile(source, key);
                    templateState.FileInfo = fileInfo;
                    templateState.Compiled = true;
                }
                catch (Exception exception)
                {
                    templateState.Compiled = false;
                    var    errors  = GetTemplateErrors(exception, templatePath);
                    string message = string.Join("\n", errors);
                    throw new ApplicationException(message);
                }
            }
            string markup = _Engine.Run(key, modelType, model);

            return(markup);
        }
예제 #6
0
        /// <summary>
        /// 从给定model生成代码字符串
        /// TODO:里面对模板进行了缓存,为了支持模板文件修改后自动清除缓存,需要实现一个文件内容监视功能
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string Generate()
        {
            ITemplateKey key = _razor.GetKey(this.TemplatePath);

            if (!_razor.IsTemplateCached(key, this.ModelType))         //第一次没缓存
            {
                string template = File.ReadAllText(this.TemplatePath); //读取模板文件内容
                _razor.AddTemplate(key, template);                     //添加模板
            }

            try
            {
                //输出
                using (TextWriter tw = new StringWriter())
                {
                    _razor.RunCompile(key, tw, this.ModelType, this._model, (DynamicViewBag)this.ViewBag); //编译模板得到结果,并缓存
                    return(tw.ToString());
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("{0},模板运行出错", this.TemplatePath), ex);
            }
        }
예제 #7
0
 public ITemplateKey GetKey(string name, ResolveType resolveType = ResolveType.Global, ITemplateKey context = null)
 {
     return(_origin.GetKey(name, resolveType, context));
 }
 /// <summary>
 /// See <see cref="RazorEngineService.Compile"/>.
 /// </summary>
 /// <param name="service"></param>
 /// <param name="name"></param>
 /// <param name="modelType"></param>
 public static void Compile(this IRazorEngineService service, string name, Type modelType = null)
 {
     service.Compile(service.GetKey(name), modelType);
 }
        /// <summary>
        /// Adds a given template to the template manager as dynamic template.
        /// </summary>
        /// <param name="service"></param>
        /// <param name="name"></param>
        /// <param name="templateSource"></param>
        public static void AddTemplate(this IRazorEngineService service, string name, ITemplateSource templateSource)
        {
            var key = service.GetKey(name);

            service.AddTemplate(key, templateSource);
        }
 /// <summary>
 /// See <see cref="RazorEngineService.Run"/>.
 /// </summary>
 /// <param name="service"></param>
 /// <param name="name"></param>
 /// <param name="writer"></param>
 /// <param name="modelType"></param>
 /// <param name="model"></param>
 /// <param name="viewBag"></param>
 public static void Run(this IRazorEngineService service, string name, TextWriter writer, Type modelType = null, object model = null, DynamicViewBag viewBag = null)
 {
     service.Run(service.GetKey(name), writer, modelType, model, viewBag);
 }
        /// <summary>
        /// Checks if a given template is already cached.
        /// </summary>
        /// <param name="service"></param>
        /// <param name="name"></param>
        /// <param name="modelType"></param>
        /// <returns></returns>
        public static bool IsTemplateCached(this IRazorEngineService service, string name, Type modelType)
        {
            var key = service.GetKey(name);

            return(service.IsTemplateCached(key, modelType));
        }
        /// <summary>
        /// Creates a string from the specified template
        /// </summary>
        /// <param name="template">The name of the Razor template (without the extension)</param>
        /// <returns>A string containing the result of the template</returns>
        public virtual string Create(string template)
        {
            var key = _service.GetKey(template);

            return(_service.RunCompile(key));
        }