예제 #1
0
        /// <summary>运行代码</summary>
        /// <param name="className"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public String Render(String className, IDictionary <String, Object> data)
        {
            TemplateBase temp = CreateInstance(className);

            temp.Data = data;
            temp.Initialize();

            try
            {
                return(temp.Render());
            }
            catch (Exception ex)
            {
                throw new TemplateExecutionException("模版执行错误!", ex);
            }
        }
예제 #2
0
        /// <summary>创建模版实例</summary>
        /// <param name="className"></param>
        /// <returns></returns>
        public TemplateBase CreateInstance(String className)
        {
            if (Status < TemplateStatus.Compile)
            {
                Compile();
            }

            if (Assembly == null)
            {
                throw new InvalidOperationException("尚未编译模版!");
            }

            if (String.IsNullOrEmpty(className))
            {
                Type[] ts = Assembly.GetTypes();
                if (ts != null && ts.Length > 0)
                {
                    // 检查是否只有一个模版类
                    Int32 n = 0;
                    foreach (Type type in ts)
                    {
                        if (!typeof(TemplateBase).IsAssignableFrom(type))
                        {
                            continue;
                        }

                        className = type.FullName;
                        if (n++ > 1)
                        {
                            break;
                        }
                    }

                    //// 干脆用第一个
                    //if (n == 0) className = ts[0].FullName;

                    // 如果只有一个模版类,则使用该类作为类名
                    if (n != 1)
                    {
                        throw new ArgumentNullException("className", "请指定模版类类名!");
                    }
                }
            }
            else
            {
                var ti = FindTemplateItem(className);
                if (ti != null)
                {
                    className = ti.ClassName;
                }
                else
                {
                    className = GetClassName(className);
                }
            }

            if (!className.Contains("."))
            {
                className = NameSpace + "." + className;
            }
            // 可能存在大小写不匹配等问题,这里需要修正
            TemplateBase temp = Assembly.CreateInstance(className, true) as TemplateBase;

            if (temp == null)
            {
                throw new Exception(String.Format("没有找到模版类[{0}]!", className));
            }

            temp.Template     = this;
            temp.TemplateItem = FindTemplateItem(className);

            return(temp);
        }