Compile() публичный Метод

Builds a text generator based on the given format.
public Compile ( string format ) : Mustache.Generator
format string The format to parse.
Результат Mustache.Generator
Пример #1
0
        public StartPage()
        {
            // Prevent duplicate instances
            if (instance != null)
                throw new DuplicateInstanceException(typeof(StartPage));

            InitializeComponent();

            // Set StartPage only dockable to document area
            DockAreas = DockAreas.Document;

            // Set up browser for interfacing
            startPageBrowser.ObjectForScripting = startPageInterface;

            // Load Resource Data
            var compiler = new FormatCompiler();
            template = compiler.Compile(Resources.StartPageTemplate);
            LayoutCSS = Resources.StartPageLayout;
            themeDark = Resources.StartPageDark;
            themeLight = Resources.StartPageLight;

            ColorThemeCSS = themeDark;

            // Load Start Page
            LoadPage();

            AttachEventHandlers(); // This one messes with the browser, so do it last.
        }
Пример #2
0
        public static Generator CompileInMemoryNestedTemplates(this FormatCompiler compiler, string format, Dictionary <string, string> templates)
        {
            var       text      = compiler.ResolveInMemoryNestedTemplates(format, templates);
            Generator generator = compiler.Compile(text);

            return(generator);
        }
Пример #3
0
 private static string ResolveInMemoryNestedTemplates(this FormatCompiler compiler, string format, Dictionary <string, string> templates)
 {
     if (templates != null && templates.Count > 0)
     {
         Dictionary <string, object> obj = new Dictionary <string, object>();
         foreach (var tuple in templates)
         {
             obj.Add(tuple.Key, tuple.Value);
         }
         var anonymos = obj.ToDynamicObject();
         while (true)
         {
             if (Regex.IsMatch(format, TemplateRegex))
             {
                 format = format.Replace("{{", OpenBraceReplacement);
                 format = format.Replace(TemplateReplacement, TemplateTag);
                 Generator generator = compiler.Compile(format);
                 format = generator.Render(anonymos);
             }
             else
             {
                 format = format.Replace(OpenBraceReplacement, "{{");
                 return(format);
             }
         }
     }
     return(format);
 }
Пример #4
0
 private void Example1_labelUpdated()
 {
     FormatCompiler compiler = new FormatCompiler();
     Generator generator = compiler.Compile("Hello, {{this}}!!!");
     string result = generator.Render("Bob");
     lblHello.Text = result;
 }
Пример #5
0
        public static Generator CompileNestedTemplates(this FormatCompiler compiler, string format)
        {
            var       text      = compiler.ResolveNestedTemplates(format, true);
            Generator generator = compiler.Compile(text);

            return(generator);
        }
Пример #6
0
        /// <summary>
        /// Builds a text generator based on the given format.
        /// </summary>
        /// <param name="format">The format to parse.</param>
        /// <returns>The text generator.</returns>
        public Generator Compile(string format)
        {
            Generator generator = compiler.Compile(format);

            generator.TagFormatted += escapeInvalidHtml;
            return(generator);
        }
Пример #7
0
 private static string TransformModel(NamedModel model, string template)
 {
     if (model == null) throw new ArgumentNullException("model");
     if (template == null) throw new ArgumentNullException("template");
     var compiler = new FormatCompiler();
     var generator = compiler.Compile(File.ReadAllText(template));
     return generator.Render(model);
 }
Пример #8
0
        public Renderer(Template template, IImageService imageService)
        {
            _template = template;
            _imageService = imageService;
            _compiler = new FormatCompiler();
            _compiler.RegisterTag(new ImgUrlTagDefinition(imageService), true);

            _generator = _compiler.Compile(_template.HTML);
        }
Пример #9
0
        public Template(string templateFile)
        {
            string template = File.ReadAllText(templateFile);

            FormatCompiler mustacheCompiler = new FormatCompiler();
            mustacheCompiler.RemoveNewLines = false;

            mustacheGenerator = mustacheCompiler.Compile(template);
        }
Пример #10
0
 private void Example4_labelUpdated()
 {
     FormatCompiler compiler = new FormatCompiler();
     Generator generator = compiler.Compile(GetLocalTemplate("SetTagTestingTemplate"));
     generator.ValueRequested += (sender, e) =>
     {
         e.Value = !(bool)(e.Value ?? false);
     };
     string result = generator.Render(new int[] { 0, 1 });
     lblSetTag.Text = result;
 }
Пример #11
0
        private static string ResolveNestedTemplates(this FormatCompiler compiler, string format, bool searchDirectory = false)
        {
            var assembly = Assembly.GetEntryAssembly();
            Dictionary <string, object> resources = new Dictionary <string, object>();
            var files = assembly.GetResources(new Regex(@".*\.mustache", RegexOptions.IgnoreCase));

            foreach (var file in files)
            {
                var fName = Path.GetFileNameWithoutExtension(file.Name).ToLowerInvariant();
                if (fName.Contains("/"))
                {
                    var lastIndex = fName.LastIndexOf('/');
                    fName = fName.Substring(lastIndex);
                }
                if (!resources.ContainsKey(fName))
                {
                    resources.Add(fName, file.CreateReadStream().ToString());
                }
            }

            if (searchDirectory)
            {
                var dirFiles = Directory.EnumerateFiles(assembly.Location, "*.mustache", SearchOption.AllDirectories);
                foreach (var file in dirFiles)
                {
                    var name = Path.GetFileNameWithoutExtension(file).ToLowerInvariant();
                    if (!resources.ContainsKey(name))
                    {
                        resources.Add(name, File.ReadAllText(file));
                    }
                }
            }
            if (resources.Count > 0)
            {
                var anonymos = resources.ToDynamicObject();
                while (true)
                {
                    if (Regex.IsMatch(format, TemplateRegex))
                    {
                        format = format.Replace("{{", OpenBraceReplacement);
                        format = format.Replace(TemplateReplacement, TemplateTag);
                        Generator generator = compiler.Compile(format);
                        format = generator.Render(anonymos);
                    }
                    else
                    {
                        format = format.Replace(OpenBraceReplacement, "{{");
                        return(format);
                    }
                }
            }
            return(format);
        }
Пример #12
0
 private void Example2_labelUpdated()
 {
     BigCustomer bigCustomer = new BigCustomer();
     bigCustomer.Customer = new Customer()
     {
         FirstName = "pawan",
         LastName = "gangad",
         Address = new Address(){City = "Pune",State = "Maharashtra",ZipCode = 411015,Line1 = "A1/6",Line2 = "Vishrant Housing Soc."}
     };
     FormatCompiler compiler = new FormatCompiler();
     Generator generator = compiler.Compile(GetLocalTemplate("TestTemplate"));
     string result = generator.Render(bigCustomer);
     lblContactInfo.Text = result;
 }
Пример #13
0
 private void Example3_labelUpdated()
 {
     BigCustomer bigCustomer = new BigCustomer();
     bigCustomer.Customer = new Customer()
     {
         FirstName = "pawan",
         LastName = "gangad",
         Address = new Address() { City = "Pune", State = "Maharashtra", ZipCode = 411015, Line1 = "A1/6", Line2 = "Vishrant Housing Soc." },
         Order = new Order() { LineItems = new List<Item>() { new Item() { ProductName = "Apple", Quantity = 6, UnitPrice = 20 }, new Item() { ProductName = "Banana", Quantity = 5, UnitPrice = 120 } } }
     };
     FormatCompiler compiler = new FormatCompiler();
     Generator generator = compiler.Compile(GetLocalTemplate("CustomerOrderTemplate"));
     string result = generator.Render(bigCustomer);
     lblCustomerOrder.Text= result;
 }
        public void ServiceHost_ClientInputRecieved(object sender, ClientInputMessage e)
        {
            Trace.WriteLine("ClientInputRecieved Recieved User Id : " + e.idUsuario, "Warning");
            try
            {
                /*Crear Blob desde un Stream*/
                // Se obtiene la cuenta de almacenamiento
                storageAccount = CloudStorageAccount.Parse(
                    CloudConfigurationManager.GetSetting("StorageConnectionString"));

                // Se crea el cliente de blobs
                blobClient = storageAccount.CreateCloudBlobClient();

                // Obtencion del container
                container = blobClient.GetContainerReference(VariablesConfiguracion.containerName);

                Int64 subid = 1;

                String mustacheTemplateStr = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "/App_Data/mustacheCloud.txt");

                //Template para generar los MDL
                FormatCompiler compiler = new FormatCompiler();
                Generator generatorMDL = compiler.Compile(mustacheTemplateStr);

                //Obtener parametros del cliente
                SimulacionParameters parametros = JsonConvert.DeserializeObject<SimulacionParameters>(e.message);

                //Barrido paramétrico
                //Especificar número de parámetros, n
                Int32 n = parametros.reacciones.Count(r => r.rate != null);
                if (n > 0)
                {
                    //Inicializo vector de inicios, fines y steps
                    LinkedList<Double> inicios = new LinkedList<Double>();
                    LinkedList<Double> fines = new LinkedList<Double>();
                    LinkedList<Double> steps = new LinkedList<Double>();
                    foreach (var reaccion in parametros.reacciones.FindAll(r => r.rate != null))
                    {
                        var inicio = reaccion.rate.rateInicio;
                        var fin = reaccion.rate.rateFin;
                        var step = reaccion.rate.rateStep;
                        inicios.AddLast(inicio);
                        fines.AddLast(fin);
                        steps.AddLast(step);
                    }

                    var iniciosArray = inicios.ToArray();
                    var finesArray = fines.ToArray();
                    var stepsArray = steps.ToArray();

                    //Defino vector lógico L para hacer barrido selectivo
                    Int32[] vectorLogico = new Int32[n];
                    for (int i = 0; i < n; i++)
                    {
                        //vectorLogico[i] = i < 5 ? 1 : 100;
                        vectorLogico[i] = 1000;
                    }

                    // Inicialización del vector j
                    Double[] j = new Double[n];
                    for (var k = 0; k < n; k++)
                    {
                        if (k == vectorLogico[k])
                        {
                            iniciosArray[k] += stepsArray[k];
                        }
                        j[k] = iniciosArray[k];
                    }

                    LinkedList<Double[]> jotas = new LinkedList<double[]>();
                    //Barrido parametrico
                    Int32 z = n - 1;
                    while (z >= 0)
                    {
                        if ((j[z] - finesArray[z]) * stepsArray[z] > 0)
                        {
                            j[z] = iniciosArray[z];
                            z--;
                        }
                        else
                        {
                            jotas.AddLast((double[])j.Clone()); //Para ver las combinaciones que creo
                            var auxId = subid;
                            Thread thread = new Thread(() => CrearMDL(e, auxId, (double[])j.Clone(), parametros, generatorMDL));
                            thread.Start();
                            //CrearMDL(e, subid, (double[])j.Clone(), parametros, generatorMDL);
                            z = n - 1;
                            subid++;
                        }
                        if (z >= 0)
                        {
                            j[z] += stepsArray[z];
                            if (z == vectorLogico[z])
                            {
                                j[z] += stepsArray[z];
                            }
                        }
                    }

                }
                else {
                    List<Double> valores = new List<double>();
                    CrearMDL(e, 0, valores.ToArray(), parametros, generatorMDL);
                }

            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.Message);
                throw;
            }
        }
Пример #15
0
        public string RenderHtml(TemplateManager templateManager)
        {
            var formatter = new FormatCompiler();

            var rootHtml = templateManager.Templates[TemplateName];
            if (string.IsNullOrEmpty(rootHtml))
            {
                return null;
            }

            var rootTemplate = formatter.Compile(rootHtml);

            var html = rootTemplate.Render(this);

            return html;
        }
Пример #16
0
        public async Task Build()
        {
            if (!Directory.Exists(_sourceDir))
            {
                Console.WriteLine($"Didn't find any pages in {_sourceDir}.");
                return;
            }

            if (!Directory.Exists(_outDir))
            {
                Console.WriteLine($"Creating directory {_outDir}");
                Directory.CreateDirectory(_outDir);
            }

            Console.WriteLine($"Building tiles...");
            var tileRoot = await BuildTileHtml();

            Console.WriteLine($"Building pages...");
            var sourceFiles = EnumerateSourceFiles(_sourceDir)
                .Select(path =>
                {
                    SourceType type;
                    switch (Path.GetExtension(path))
                    {
                        case ".html":
                            type = SourceType.Html;
                            break;
                        case ".md":
                        case ".mdown":
                        case ".markdown":
                            type = SourceType.Markdown;
                            break;
                        default:
                            type = SourceType.Other;
                            break;
                    }

                    return new {path, type};
                })
                .Where(x => x.type != SourceType.Other)
                .ToList();
            
            Console.WriteLine($"Found {sourceFiles.Count} files in {_sourceDir}");
            
            var markdownParser = new Markdown();
            var formatCompiler = new FormatCompiler {RemoveNewLines = false};
            var markdownGenerator = formatCompiler.Compile(_templateManager.Templates["skeleton"]);
            foreach (var sourceFile in sourceFiles)
            {
                // dir structure should be maintained from source to out,
                // need to get the relative path from the source file to the root of all source files.
                var sourceToWebrootPath = GetRelativePath(sourceFile.path, _sourceDir);
                var sourceFileName = Path.GetFileNameWithoutExtension(sourceFile.path);
                var webrootToSourceFileDirPath = GetRelativePath(_sourceDir, Path.GetDirectoryName(sourceFile.path));

                var outFileName = $"{sourceFileName.ToLowerInvariant()}.html";
                var outFilePath = Path.Combine(_outDir, webrootToSourceFileDirPath, outFileName);
                
                string pageHtml;
                if (sourceFile.type == SourceType.Html)
                {
                    var pageTemplate = File.ReadAllText(sourceFile.path);
                    var compiler = formatCompiler.Compile(pageTemplate);
                    var pageData = new
                    {
                        title = sourceFileName,
                        tiles = tileRoot,
                        webroot = sourceToWebrootPath.NullIfEmpty() ?? ".",
                        date = ""
                    };
                    pageHtml = compiler.Render(pageData);
                }
                else if (sourceFile.type == SourceType.Markdown)
                {
                    var pageLines = File.ReadAllLines(sourceFile.path).ToList();
                    var pageMeta = PageMeta.Parse(pageLines);

                    var articleLines = pageLines.SkipWhile(line => line.StartsWith(PageMeta.MD_META_PREFIX));
                    var articleMarkdown = string.Join(Environment.NewLine, articleLines);
                    var articleHtml = markdownParser.Transform(articleMarkdown);

                    var pageData = new
                    {
                        title = pageMeta.Title ?? sourceFileName.Humanize("-"),
                        content = articleHtml,
                        tiles = tileRoot,
                        webroot = sourceToWebrootPath.NullIfEmpty() ?? ".",
                        date = pageMeta.Date?.Humanize() ?? ""
                    };

                    pageHtml = markdownGenerator.Render(pageData);
                }
                else
                {
                    throw new Exception($"Source type {sourceFile.type} not supported");
                }

                var outFileDir = Path.GetDirectoryName(outFilePath);
                if (!Directory.Exists(outFileDir))
                {
                    Directory.CreateDirectory(outFileDir);
                }

                File.WriteAllText(outFilePath, pageHtml);

                var colour = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"Built {outFilePath.Replace(outFileDir, "")}");
                Console.ForegroundColor = colour;
            }
        }
Пример #17
0
        static void Main()
        {
            //testing
            //TestExistingTemplates.Test();

            var orderModel = new Order()
                                {
                                    Name = "Bob's order",
                                    TransactionID = "10000",
                                    OrderItems = new List<OrderItem>()
                                                {
                                                    new OrderItem
                                                    {
                                                        ProductTypeName = "MobileRecharge",
                                                        Detail1 = "Mobile Detail 1",
                                                        Detail2 = "Mobile Detail 2",
                                                        Amount = new Money{Value = 10.4, Currency = "USD"},
                                                        PromotionalDiscount = "100 USD"
                                                    },
                                                    new OrderItem
                                                    {
                                                        ProductTypeName = "ILDTopup",
                                                        Detail1 = "ILD Detail 1",
                                                        Detail2 = "ILD Detail 2",
                                                    },
                                                    new OrderItem
                                                    {
                                                        ProductTypeName = "Nauta",
                                                        Detail1 = "Nauta Detail 1",
                                                        Detail2 = "Nauta Detail 2"
                                                    }
                                                }
                                };

            var dict = new Dictionary<string, object>
                        {
                            {"Value1", "Value1"}
                        };

            ITemplate template = new HtmlTemplate();

            FormatCompiler compiler = new FormatCompiler();

            var templateParser = new MustacheTemplateConverter();

            var convertDingConditionalToMustache = templateParser.ConvertDingConditionalToMustache(template.Template);
            Generator generator = compiler.Compile(convertDingConditionalToMustache);
            generator.KeyNotFound += (obj, args) =>
                                    {
                                        args.Substitute = string.Empty;
                                        args.Handled = true;
                                    };

            string result = generator.Render(MyConvert.DictionaryToDynamic(dict));

            Console.ReadKey();
        }