예제 #1
0
        private static void GenerateForOneFile(DatabaseSchema Schema, String TemplatePath, String OutputPath)
        {
            var    GeneratorSyntax = SchemaToGeneratorSyntax(Schema);
            String fileContents    = File.ReadAllText(TemplatePath, System.Text.Encoding.Default);

            DotLiquid.Template templateLiquid = DotLiquid.Template.Parse(@fileContents); // Parses and compiles the template
            String             compiledOutput = templateLiquid.Render(Hash.FromAnonymousObject(new { tables = GeneratorSyntax }, true));

            compiledOutput = compiledOutput.Replace(@"'}'}'", "}}");
            compiledOutput = compiledOutput.Replace(@"'{'{'", "{{");
            File.WriteAllText(OutputPath, compiledOutput);
        }
예제 #2
0
        public BenchRenderers()
        {
            var parsers = new BenchParsers();

            _scribanTemplate    = parsers.TestScriban();
            _dotLiquidTemplate  = parsers.TestDotLiquid();
            _stubbleTemplate    = parsers.TestStubble();
            _stubbleSettings    = new Stubble.Core.Settings.RendererSettingsBuilder().BuildSettings();
            _nustacheTemplate   = parsers.TestNustache();
            _handlebarsTemplate = parsers.TestHandlebars();
            _cottleTemplate     = parsers.TestCottle();
            _fluidTemplate      = parsers.TestFluid();
            _razorTemplate      = parsers.TestRazor();

            const int ProductCount = 500;

            _products          = new List <Product>(ProductCount);
            _scribanProducts   = new List <ScriptObject>();
            _dotLiquidProducts = new List <DotLiquid.Hash>(ProductCount);
            var cottleValues = new List <Cottle.Value>();

            for (int i = 0; i < ProductCount; i++)
            {
                var product = new Product("Name" + i, i, Lorem);
                _products.Add(product);

                var hash = new Hash()
                {
                    ["name"] = product.Name, ["price"] = product.Price, ["description"] = product.Description
                };
                _dotLiquidProducts.Add(hash);

                var obj = new ScriptObject {
                    ["name"] = product.Name, ["price"] = product.Price, ["description"] = product.Description
                };
                _scribanProducts.Add(obj);
                cottleValues.Add(new Cottle.Values.ReflectionValue(product));
            }

            _liquidTemplateContext = new LiquidTemplateContext();

            // For Cottle, we match the behavior of Scriban that is accessing the Truncate function via an reflection invoke
            // In Scriban, we could also have a direct Truncate function, but it is much less practical in terms of declaration
            _cottleStringStore             = new Dictionary <Cottle.Value, Cottle.Value>();
            _cottleStringStore["truncate"] = new Cottle.Functions.NativeFunction((values, store, Output) =>
            {
                if (values.Count != 2)
                {
                    throw new InvalidOperationException("Unexpected number of arguments for truncate function");
                }
                return(StringFunctions.Truncate(values[0].AsString, Convert.ToInt32(values[1].AsNumber)));
            }, 2);
        }
예제 #3
0
파일: Program.cs 프로젝트: yzbai/scriban
        public BenchRenderers()
        {
            var parsers = new BenchParsers();

            _scribanTemplate    = parsers.TestScriban();
            _dotLiquidTemplate  = parsers.TestDotLiquid();
            _stubbleTemplate    = parsers.TestStubble();
            _stubbleSettings    = new Stubble.Core.Settings.RendererSettingsBuilder().BuildSettings();
            _nustacheTemplate   = parsers.TestNustache();
            _handlebarsTemplate = parsers.TestHandlebars();
            _cottleTemplate     = parsers.TestCottle();
            _fluidTemplate      = parsers.TestFluid();

            const int ProductCount = 500;

            _products          = new List <Product>(ProductCount);
            _scribanProducts   = new List <ScriptObject>();
            _dotLiquidProducts = new List <DotLiquid.Hash>(ProductCount);
            var cottleProducts = new List <Cottle.Value>();

            for (int i = 0; i < ProductCount; i++)
            {
                var product = new Product("Name" + i, i, Lorem);
                _products.Add(product);

                var hash = new Hash()
                {
                    ["name"] = product.Name, ["price"] = product.Price, ["description"] = product.Description
                };
                _dotLiquidProducts.Add(hash);

                var obj = new ScriptObject {
                    ["name"] = product.Name, ["price"] = product.Price, ["description"] = product.Description
                };
                _scribanProducts.Add(obj);

                var value = new Dictionary <Cottle.Value, Cottle.Value> {
                    ["name"] = product.Name, ["price"] = product.Price, ["description"] = product.Description
                };
                cottleProducts.Add(value);
            }

            _cottleProducts = cottleProducts;

            _templateContext = new TemplateContext();
            _templateContext.BuiltinObject["truncate"] = ((ScriptObject)_templateContext.BuiltinObject["string"])["truncate"];

            // For Cottle, we match the behavior of Scriban that is accessing the Truncate function via an reflection invoke
            // In Scriban, we could also have a direct Truncate function, but it is much less practical in terms of declaration
            _cottleStringStore             = new Dictionary <Cottle.Value, Cottle.Value>();
            _cottleStringStore["truncate"] = new Cottle.Functions.NativeFunction(values => StringFunctions.Truncate(values[0].AsString, Convert.ToInt32(values[1].AsNumber)), 2);
        }
예제 #4
0
        public static string Render(string templateString, object model)
        {
            DotLiquid.Template template = DotLiquid.Template.Parse(templateString);

            Hash mod = new Hash();

            if (model != null)
            {
                mod = Hash.FromAnonymousObject(model);
            }

            return(template.Render(mod));
        }
예제 #5
0
        private void CreateTemplate(string _text, string _workingDir)
        {
            try
            {
                //Log.I("working dir {0}", _workingDir);
                TagUnityAsset.WorkingDir = _workingDir;

                var _template = DL.Template.Parse(_text);
                m_Template = _template;
            }
            catch (Exception _err)
            {
                Log.E(_err);
            }
        }
예제 #6
0
        private static void GenerateForMultipleFiles(DatabaseSchema Schema, String TemplatePath, String OutputPath)
        {
            String fileContents    = File.ReadAllText(TemplatePath, System.Text.Encoding.Default);
            var    GeneratorSyntax = SchemaToGeneratorSyntax(Schema);

            foreach (var Table in GeneratorSyntax)
            {
                DotLiquid.Template templateLiquidMultiple = DotLiquid.Template.Parse(@fileContents); // Parses and compiles the template
                String             compiledOutputMultiple = templateLiquidMultiple.Render(Hash.FromAnonymousObject(new { table = Table }, true));
                DotLiquid.Template templateLiquidFileName = DotLiquid.Template.Parse(TemplatePath);  // Parses and compiles the template
                String             compiledFileName       = templateLiquidFileName.Render(Hash.FromAnonymousObject(new { table = Table }, true));
                compiledOutputMultiple = compiledOutputMultiple.Replace(AppConfigHelper.GetRightTagUnprocessing(), "}}");
                compiledOutputMultiple = compiledOutputMultiple.Replace(AppConfigHelper.GetLeftTagUnprocessing(), "{{");
                File.WriteAllText(compiledFileName, compiledOutputMultiple, System.Text.Encoding.Default);
            }
        }
예제 #7
0
        public static void SetPath(int select)
        {
            switch (select)
            {
            case 0:
                TemplatePathCheckPrint = Func(PathCheckPrint);
                break;

            case 1:
                TemplatePathReturnPrint = Func(PathReturnPrint);
                break;

            case 2:
                TemplatePathRaportPricePrint = Func(PathRaportPricePrint);
                break;
            }
        }
예제 #8
0
    public static void Prepare()
    {
        compile = DotLiquid.Template.Parse(template);
        List <object> rows = new List <object>();

        for (int i = 0; i < 100; i++)
        {
            rows.Add(new Dictionary <string, object> {
                { "ID", i },
                { "Message", string.Format("message {0}", i) },
                { "Print", i % 2 == 0 },
            });
        }
        hash = DotLiquid.Hash.FromDictionary(new Dictionary <string, object> {
            { "rows", rows }
        });
    }
예제 #9
0
        public HttpResponseMessage GetliquidPage()
        {
            string templatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "article3.html");

            using (StreamReader reader = new StreamReader(templatePath))
            {
                string strTemp = reader.ReadToEnd();

                var data = TemplateData.Create();

                DotLiquid.Template template = DotLiquid.Template.Parse(strTemp);               // Parses and compiles the template
                string             result   = template.Render(Hash.FromAnonymousObject(data)); // Renders the output

                var response = new HttpResponseMessage();
                response.Content = new StringContent(result);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");

                return(response);
            }
        }
예제 #10
0
        /// <summary>
        /// Handles the Click event of the lbGenerate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbGenerate_Click(object sender, EventArgs e)
        {
            var page  = new PageService(new RockContext()).Get(ppPage.SelectedValueAsId().Value);
            var pages = PageAndDescendants(page);

            string lavaTemplate = GetAttributeValue("LavaTemplate");
            var    mergeFields  = Rock.Lava.LavaHelper.GetCommonMergeFields(RockPage);

            mergeFields.Add("RootPage", page);
            mergeFields.Add("Pages", pages);
            mergeFields.Add("ReversePages", pages);

            DotLiquid.Template         template   = DotLiquid.Template.Parse(lavaTemplate);
            DotLiquid.RenderParameters parameters = new DotLiquid.RenderParameters
            {
                LocalVariables = DotLiquid.Hash.FromDictionary(mergeFields),
                Filters        = new Type[] { typeof(LavaAdditions) }
            };
            lResults.Text    = template.Render(parameters).EncodeHtml();
            pResults.Visible = true;
        }
예제 #11
0
            private void ReadContentFromPath(string _path)
            {
                try
                {
                    using (var _f = new System.IO.StreamReader(_path))
                    {
                        m_Content = _f.ReadToEnd();

                        if (m_Content.Contains("{%") || m_Content.Contains("{{"))
                        {
                            //Log.I("Processing Template " + _path);
                            // Backup WorkingDir
                            string _lastWorkDir = TagUnityAsset.WorkingDir;

                            // Modify the WorkingDir
                            TagUnityAsset.WorkingDir = System.IO.Path.GetDirectoryName(_path);

                            try
                            {
                                m_Template = DL.Template.Parse(m_Content);
                            }
                            catch (Exception _errTemplate)
                            {
                                Log.E(_errTemplate);
                                m_Content = null;
                            }

                            // Restore WorkingDir
                            TagUnityAsset.WorkingDir = _lastWorkDir;
                        }
                    }
                }
                catch (Exception _err)
                {
                    Log.E(_err);
                    m_Content = null;
                }
            }
예제 #12
0
        private string GetOrderStatusPartial()
        {
            int    orderId = _order.OrderId.Value;
            string webLink = string.Format(SettingsService.EmailServiceOrderUrl, _appNameId, orderId);

            string resOrder      = "Order";
            string resView_Order = "View Order";

            string templateStr = GetLiquidFileAsString("OrderStatusPartial.liquid");

            DotLiquid.Template template = Template.Parse(templateStr);
            var paramaters = new RenderParameters(CultureInfo.CurrentCulture)
            {
                LocalVariables = Hash.FromAnonymousObject(new
                {
                    webLink,
                    orderId,
                    resOrder,
                    resView_Order
                })
            };

            return(template.Render(paramaters));;
        }
예제 #13
0
 private void CreateTemplate(string _text)
 {
     try
     {
         var _template = DL.Template.Parse(_text);
         m_Template = _template;
     }
     catch (Exception _err)
     {
         Log.E(_err);
     }
 }
예제 #14
0
        /// <summary>
        /// Genera el contenido html
        /// </summary>
        /// <param name="reporte">Nombre del reporte</param>
        /// <param name="parametros">Parametros</param>
        /// <param name="format">Formato</param>
        /// <returns></returns>
        public static string Render(string reporte, string parametros, EnumRenderFormat format)
        {
            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("es-ES");
            System.Threading.Thread.CurrentThread.CurrentCulture = ci;
            DotLiquid.Template.RegisterFilter(typeof(Reports.LiquidFilters));


            var obj_parametros = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, object> >(parametros);

            string texto = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/Reports/" + reporte + ".html"));

            var xml = XDocument.Load(HttpContext.Current.Server.MapPath("~/Reports/" + reporte + ".data"));
            Dictionary <string, object> objeto = new Dictionary <string, object>();

            if (xml != null)
            {
                XNamespace ns      = xml.Root.GetDefaultNamespace();
                var        x       = xml.Descendants().Where(q => q.Name.LocalName == "DataSets").FirstOrDefault();
                string     strconn = xml.Descendants().Where(q => q.Name.LocalName == "DataSource").FirstOrDefault().Value;
                x.Elements().ToList().ForEach((e) =>
                {
                    bool IsMultiRecords = e.Attribute("IsMultiRecords") != null ? e.Attribute("IsMultiRecords").Value == "1" : false;
                    string Type         = e.Attribute("type") == null ? "query" : e.Attribute("type").Value;
                    string Name         = e.Attribute("name").Value;
                    string SQL          = e.Element(e.GetDefaultNamespace() + "SQL").Value;

                    System.Data.CommandType commandType = Type == "query" ? System.Data.CommandType.Text : System.Data.CommandType.StoredProcedure;
                    using (var conn = DbFactory.Conn(strconn))
                    {
                        conn.Open();

                        DynamicParameters parameters = new DynamicParameters();
                        e.Element(e.GetDefaultNamespace() + "Parameters").Elements().ToList().ForEach((a) =>
                        {
                            string parameterName      = a.Attribute("name").Value;
                            object value              = obj_parametros[parameterName];
                            System.Data.DbType dbType = GetType(a.Attribute("type") == null ? "string" : a.Attribute("type").Value);
                            parameters.Add(parameterName, value, dbType);
                        });
                        if (IsMultiRecords) //Si es tiene mas de una fila
                        {
                            List <object> datos = new List <object>();
                            conn.Query(sql: SQL, param: parameters, commandType: commandType).ToList().ForEach((f) =>
                            {
                                datos.Add(DapperHelpers.ToExpandoObject(f));
                            });
                            objeto.Add(Name, datos);
                        }

                        else
                        {
                            var firstOrDefault = conn.Query(sql: SQL, param: parameters, commandType: commandType).FirstOrDefault();
                            objeto.Add(Name, firstOrDefault);
                        }
                    }
                });
            }
            //variable globales que pueden ser usadas en el reporte
            objeto.Add("RenderFormat", format.ToString());
            objeto.Add("Today", DateTime.Now);
            DotLiquid.Template template = DotLiquid.Template.Parse(texto);
            string             html     = template.Render(Hash.FromDictionary(objeto));

            return(html);
        }
예제 #15
0
파일: Block.cs 프로젝트: mwadams/dotliquid
        /// <summary>
        /// Parses a list of tokens
        /// </summary>
        /// <param name="tokens"></param>
        protected override void Parse(List <string> tokens)
        {
            NodeList = NodeList ?? new List <object>();
            NodeList.Clear();

            string token;

            while ((token = tokens.Shift()) != null)
            {
                Match isTagMatch = IsTag.Match(token);
                if (isTagMatch.Success)
                {
                    Match fullTokenMatch = FullToken.Match(token);
                    if (fullTokenMatch.Success)
                    {
                        // If we found the proper block delimitor just end parsing here and let the outer block
                        // proceed
                        if (BlockDelimiter == fullTokenMatch.Groups[1].Value)
                        {
                            EndTag();
                            return;
                        }

                        // Fetch the tag from registered blocks
                        Tag tag;
                        if ((tag = Template.CreateTag(fullTokenMatch.Groups[1].Value)) != null)
                        {
                            tag.Initialize(fullTokenMatch.Groups[1].Value, fullTokenMatch.Groups[2].Value, tokens);
                            NodeList.Add(tag);

                            // If the tag has some rules (eg: it must occur once) then check for them
                            tag.AssertTagRulesViolation(NodeList);
                        }
                        else
                        {
                            // This tag is not registered with the system
                            // pass it to the current block for special handling or error reporting
                            UnknownTag(fullTokenMatch.Groups[1].Value, fullTokenMatch.Groups[2].Value, tokens);
                        }
                    }
                    else
                    {
                        throw new SyntaxException(Liquid.ResourceManager.GetString("BlockTagNotTerminatedException"), token, Liquid.TagEnd);
                    }
                }
                else if (IsVariable.Match(token).Success)
                {
                    NodeList.Add(CreateVariable(token));
                }
                else if (token == string.Empty)
                {
                    // Pass
                }
                else
                {
                    NodeList.Add(token);
                }
            }

            // Make sure that its ok to end parsing in the current block.
            // Effectively this method will throw an exception unless the current block is
            // of type Document
            AssertMissingDelimitation();
        }
예제 #16
0
        private static object Liquidize(object obj)
        {
            if (obj == null)
            {
                return(obj);
            }
            if (obj is ILiquidizable)
            {
                return(((ILiquidizable)obj).ToLiquid());
            }
            if (obj is string)
            {
                return(obj);
            }
            if (obj is IEnumerable)
            {
                return(obj);
            }
            if (obj.GetType().IsPrimitive)
            {
                return(obj);
            }
            if (obj is decimal)
            {
                return(obj);
            }
            if (obj is DateTime)
            {
                return(obj);
            }
            if (obj is DateTimeOffset)
            {
                return(obj);
            }
            if (obj is TimeSpan)
            {
                return(obj);
            }
            if (obj is Guid)
            {
                return(obj);
            }
            if (obj is Enum)
            {
                return(obj);
            }
            if (TypeUtility.IsAnonymousType(obj.GetType()))
            {
                return(obj);
            }
            if (obj is KeyValuePair <string, object> )
            {
                return(obj);
            }
            var safeTypeTransformer = Template.GetSafeTypeTransformer(obj.GetType());

            if (safeTypeTransformer != null)
            {
                return(safeTypeTransformer(obj));
            }
            if (obj.GetType().GetCustomAttributes(typeof(LiquidTypeAttribute), false).Any())
            {
                var attr = (LiquidTypeAttribute)obj.GetType().GetCustomAttributes(typeof(LiquidTypeAttribute), false).First();
                return(new DropProxy(obj, attr.AllowedMembers));
            }

            throw new SyntaxException(Liquid.ResourceManager.GetString("ContextObjectInvalidException"), obj.ToString());
        }