// https://github.com/antlr/antlr4/issues/192#issuecomment-15238595 public void It_Should_Not_Bog_On_Raw_Text_With_Adaptive_Prediction() { // Arrange DateTime start = DateTime.Now; Logger.Log("STARTING..."); int iterations = 100; String template = "<html><body>\r\n"; for (int i = 0; i < iterations; i++) { template += "{% for x in (1..10) %} Test {{ x }}{% endfor %}"; for (int j = 0; j < 100; j++) { template += " Raw text "+j; } } template += "</body>\r\n</html>"; ITemplateContext ctx = new TemplateContext() .WithAllFilters(); // Act var result = RenderingHelper.RenderTemplate(template, ctx); Logger.Log(result); // Assert var end = DateTime.Now; TimeSpan timeDiff = end - start; Logger.Log("ELAPSED: " + timeDiff.TotalMilliseconds); Assert.That(timeDiff.Milliseconds < 1000); //Assert.Fail("Not Implemented Yet"); }
/// <summary> /// 转换为 Boolean /// </summary> /// <param name="context">TemplateContext</param> /// <returns></returns> public virtual Boolean ToBoolean(TemplateContext context) { Object value = Parse(context); if (value == null) return false; switch (value.GetType().FullName) { case "System.Boolean": return (Boolean)value; case "System.String": return !String.IsNullOrEmpty(value.ToString()); case "System.UInt16": case "System.UInt32": case "System.UInt64": case "System.Int16": case "System.Int32": case "System.Int64": return value.ToString()!="0"; case "System.Decimal": return (Decimal)value != 0; case "System.Double": return (Double)value != 0; case "System.Single": return (Single)value != 0; } return value != null; }
public override string TheType(TemplateContext context) { var item = context.Item as IMappingsConnectable; if (item != null) return item.ContextTypeName; return base.TheType(context); }
private void Excute(TemplateContext context, StringBuilder writer) { this.Initial.Parse(context); //如果标签为空,则直接为false,避免死循环以内存溢出 Boolean run; if (this.Test == null) { run = false; } else { run = this.Test.ToBoolean(context); } while (run) { for (Int32 i = 0; i < this.Children.Count; i++) { this.Children[i].Parse(context, writer); } if (this.Do != null) { this.Do.Parse(context); } run = this.Test == null ? true : this.Test.ToBoolean(context); } }
public override void Evaluate(TemplateContext context) { for (int i = 0; i < Statements.Count; i++) { var statement = Statements[i]; var expressionStatement = statement as ScriptExpressionStatement; var isAssign = expressionStatement?.Expression is ScriptAssignExpression; context.Result = null; statement.Evaluate(context); // Top-level assignment expression don't output anything if (isAssign) { context.Result = null; } else if (context.Result != null && context.FlowState != ScriptFlowState.Return && context.EnableOutput) { context.Write(Span, context.Result); context.Result = null; } // If flow state is different, we need to exit this loop if (context.FlowState != ScriptFlowState.None) { break; } } }
public override object Eval(TemplateContext context) { object val = null; for (int i = 0; i < parts.Count; i++) { // get variable from context if (i == 0 && !parts[i].IsMethod) { val = EvalContextVariable(parts[i], context); } // call built-in function else if (i == 0 && parts[i].IsMethod) { BuiltinFunctions target = new BuiltinFunctions(); target.Context = context; target.Line = parts[i].Line; target.Column = parts[i].Column; val = EvalMethod(target, parts[i], context); } // call public property else if(i > 0 && !parts[i].IsMethod) // property { val = EvalProperty(val, parts[i], context); } // call public method else if (i > 0 && parts[i].IsMethod) // property { val = EvalMethod(val, parts[i], context); } } return val; }
public override void Eval(TemplateContext context, System.IO.StringWriter writer) { // evaluate indicies object objStartIdx = StartIndex.Eval(context); object objEndIdx = EndIndex.Eval(context); // check indicies if (!(objStartIdx is Int32)) throw new ParserException("Start index expression should evaluate to integer.", StartIndex.Line, StartIndex.Column); if (!(objEndIdx is Int32)) throw new ParserException("End index expression should evaluate to integer.", StartIndex.Line, StartIndex.Column); int startIdx = Convert.ToInt32(objStartIdx); int endIdx = Convert.ToInt32(objEndIdx); int step = startIdx < endIdx ? 1 : -1; endIdx += step; int i = startIdx; do { context.Variables[IndexIdentifier] = i; // evaluate statements foreach (Statement stm in Statements) stm.Eval(context, writer); i += step; } while (i != endIdx); // cleanup vars context.Variables.Remove(IndexIdentifier); }
public override void Modify(object templateInstance, MemberInfo info, TemplateContext ctx) { base.Modify(templateInstance, info, ctx); string strRegex = @"_(?<name>[a-zA-Z0-9]+)_"; bool replaced = false; var newName = Regex.Replace(info.Name, strRegex, _ => { var name = _.Groups["name"].Value; try { replaced = true; return (string) ctx.GetTemplateProperty(templateInstance, name); } catch (TemplateException ex) { return ctx.Item.Name; } }); if (!replaced && NameFormat != null) { ctx.CurrentMember.Name = string.Format(NameFormat, ctx.Item.Name.Clean()); } else { ctx.CurrentMember.Name = newName.Clean(); } }
/// <summary> /// 解析标签 /// </summary> /// <param name="context">上下文</param> /// <param name="writer">writer</param> public override void Parse(TemplateContext context, System.IO.TextWriter writer) { if (Source != null) { Excute(Source.Parse(context), context, writer); } }
public virtual void WriteCode(TemplateContext ctx, ActionNode node) { var varStatement = ctx.CurrentDeclaration._private_(node.Meta.FullName, node.VarName); varStatement.InitExpression = new CodeObjectCreateExpression(node.Meta.FullName); foreach (var item in node.GraphItems.OfType<IActionIn>()) { var contextVariable = item.Item; if (contextVariable == null) continue; ctx._("{0}.{1} = {2}", varStatement.Name, item.Name, item.VariableName); } ctx._("{0}.System = System", varStatement.Name); foreach (var item in node.GraphItems.OfType<ActionBranch>()) { var branchOutput = item.OutputTo<SequenceItemNode>(); if (branchOutput == null) continue; if (DebugSystem.IsDebugMode) ctx._("{0}.{1} = ()=> {{ System.StartCoroutine({2}()); }}", varStatement.Name, item.Name, item.VariableName); else ctx._("{0}.{1} = {2}", varStatement.Name, item.Name, item.VariableName); } ctx._("{0}.Execute()", varStatement.Name); node.WriteActionOutputs(ctx); }
public override void Evaluate(TemplateContext context) { switch (Operator) { case ScriptUnaryOperator.Not: { var value = context.Evaluate(Right); context.Result = !ScriptValueConverter.ToBool(value); } break; case ScriptUnaryOperator.Negate: case ScriptUnaryOperator.Plus: { var value = context.Evaluate(Right); bool negate = Operator == ScriptUnaryOperator.Negate; var customType = value as IScriptCustomType; if (customType != null) { context.Result = customType.EvaluateUnaryExpression(this); } else if (value != null) { if (value is int) { context.Result = negate ? -((int) value) : value; } else if (value is double) { context.Result = negate ? -((double) value) : value; } else if (value is float) { context.Result = negate ? -((float) value) : value; } else if (value is long) { context.Result = negate ? -((long) value) : value; } else { throw new ScriptRuntimeException(this.Span, $"Unexpected value [{value} / Type: {value?.GetType()}]. Cannot negate(-)/positive(+) a non-numeric value"); } } } break; case ScriptUnaryOperator.FunctionAlias: context.Result = context.Evaluate(Right, true); break; case ScriptUnaryOperator.FunctionParametersExpand: // Function parameters expand is done at the function level, so here, we simply return the actual list Right?.Evaluate(context); break; default: throw new ScriptRuntimeException(Span, $"Operator [{Operator}] is not supported"); } }
public void TestFrontMatter() { var options = new ParserOptions() {Mode = ScriptMode.FrontMatter}; var template = ParseTemplate(@"{{ variable = 1 name = 'yes' }} This is after the frontmatter: {{ name }} {{ variable + 1 }}", options); // Make sure that we have a front matter Assert.NotNull(template.Page.FrontMatter); var context = new TemplateContext(); // Evaluate front-matter var frontResult = context.Evaluate(template.Page.FrontMatter); Assert.Null(frontResult); // Evaluate page-content context.Evaluate(template.Page); var pageResult = context.Output.ToString(); Assert.AreEqual(@"This is after the frontmatter: yes 2", pageResult); }
public void It_Should_Dereference_A_Nested_Dictionary() { // Arrange var dict3 = new Dictionary<String, IExpressionConstant> { {"str", new StringValue("Dict 3")}, }; DictionaryValue dictValue3 = new DictionaryValue(dict3); var dict2 = new Dictionary<String, IExpressionConstant> { {"dict3", dictValue3} }; DictionaryValue dictValue2 = new DictionaryValue(dict2); var dict = new Dictionary<String, IExpressionConstant> { {"dict2", dictValue2} }; DictionaryValue dictValue = new DictionaryValue(dict); ITemplateContext ctx = new TemplateContext() .DefineLocalVariable("dict1", dictValue); // Act var result = RenderingHelper.RenderTemplate("Result : {{dict1.dict2.dict3.str}}->{% if dict1.dict2.dict3.str == \"Dict 2\" %}Dict2{% elseif dict1.dict2.dict3.str == \"Dict 3\" %}Dict3{%endif%}", ctx); // Assert Assert.That(result, Is.EqualTo("Result : Dict 3->Dict3")); }
protected override Window CreateWindowCore(TemplateContext context, ICollection<Controller> controllers, bool isMain, bool activateControllersImmediatelly) { Tracing.Tracer.LogVerboseValue("WinApplication.CreateWindowCore.activateControllersImmediatelly", activateControllersImmediatelly); var windowCreatingEventArgs = new WindowCreatingEventArgs(); OnWindowCreating(windowCreatingEventArgs); return windowCreatingEventArgs.Handled? windowCreatingEventArgs.Window : new XpandWebWindow(this, context, controllers, isMain, activateControllersImmediatelly); }
public override void Evaluate(TemplateContext context) { if (Name != null) { context.SetValue(Name, this); } }
/// <summary> /// 解析标签 /// </summary> /// <param name="context">上下文</param> /// <param name="write">write</param> public override void Parse(TemplateContext context, System.IO.TextWriter write) { for (Int32 i = 0; i < Children.Count; i++) { Children[0].Parse(context, write); } }
public override void Eval(TemplateContext context, System.IO.StringWriter writer) { // evaluate test condition bool result = EvalCondition(Condition, context); if (result) { foreach (Statement stm in TrueStatements) stm.Eval(context, writer); return; } else { // process else if statements foreach (ElseIfStatement stm in ElseIfStatements) { if (EvalCondition(stm.Condition, context)) { stm.Eval(context, writer); return; } } // process else foreach (Statement stm in FalseStatements) stm.Eval(context, writer); } }
public override void WriteCode(ISequenceVisitor visitor, TemplateContext ctx) { //base.WriteCode(ctx); var handlerMethod = ctx.CurrentDeclaration.protected_virtual_func(typeof(void), Name, Name.ToLower()); var handlerInvoke = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), Name); foreach (CodeParameterDeclarationExpression item in ctx.CurrentMethod.Parameters) { handlerMethod.Parameters.Add(item); handlerInvoke.Parameters.Add(new CodeVariableReferenceExpression(item.Name)); } //foreach (var item in AllContextVariables) //{ // if (item.IsSubVariable) continue; // var type = item.SourceVariable == null ? item.Name : item.SourceVariable.RelatedTypeName; // handlerMethod.Parameters.Add(new CodeParameterDeclarationExpression( // type , item.AsParameter)); // handlerInvoke.Parameters.Add(new CodeVariableReferenceExpression(item.ToString())); //} ctx.CurrentStatements.Add(handlerInvoke); //ctx.PushStatements(handlerMethod.Statements); //ctx.PopStatements(); }
private void Excute(TemplateContext context, System.IO.TextWriter writer) { this._initial.Parse(context); //如果标签为空,则直接为false,避免死循环以内存溢出 Boolean run; if (this._test == null) { run = false; } else { run = this._test.ToBoolean(context); } while (run) { for (Int32 i = 0; i < Children.Count; i++) { Children[i].Parse(context, writer); } if (this._dothing != null) { this._dothing.Parse(context); } run = this._test == null ? true : this._test.ToBoolean(context); } }
private object EvalContextVariable(IdentifierPart variable, TemplateContext context) { object val = null; TemplateContext lookupContext = context; while (lookupContext != null) { if (lookupContext.Variables.ContainsKey(variable.Name)) { val = lookupContext.Variables[variable.Name]; break; // found local scope var - stop looking } // look into parent scope lookupContext = lookupContext.ParentContext; } // get from context if (val == null) return null; // evaluate index expression if required val = EvalIndexer(val, variable, context); return val; }
public override Object Parse(Object baseValue, TemplateContext context) { if (baseValue != null) { Object[] args = new Object[this.Children.Count]; Type[] argsType = new Type[this.Children.Count]; for (Int32 i = 0; i < this.Children.Count; i++) { args[i] = this.Children[i].Parse(context); if (args[i] != null) { argsType[i] = args[i].GetType(); } else { } } Object result = Excute(baseValue, context, args, argsType); if (result != null) { return result; } result = Common.ReflectionHelpers.GetPropertyValue(baseValue, this.Name); if (result != null && result is FuncHandler) { return (result as FuncHandler).Invoke(args); } } return null; }
public override void Parse(TemplateContext context, StringBuilder writer) { if (this.Source != null) { Excute(this.Source.Parse(context), context, writer); } }
/// <summary> /// 解析标签 /// </summary> /// <param name="context">上下文</param> /// <param name="baseValue">baseValue</param> public override Object Parse(Object baseValue, TemplateContext context) { if (baseValue != null) { Object[] args = new Object[Children.Count]; for (Int32 i = 0; i < Children.Count; i++) { args[i] = Children[i].Parse(context); } Object result = Dynamic.DynamicHelper.ExcuteMethod(baseValue, this._name, args); if (result != null) { return result; } result = Dynamic.DynamicHelper.GetPropertyOrField(baseValue, this._name); if (result != null && result is FuncHandler) { return (result as FuncHandler).Invoke(args); } } return null; }
private void ParseCollection(TagCollection tags, TemplateContext context, System.IO.TextWriter write) { for (Int32 i = 0; i < tags.Count; i++) { write.Write( tags[i].Parse(context)); } }
public override void Eval(TemplateContext context, System.IO.StringWriter writer) { // locate template if (!context.Templates.ContainsKey(templateName)) throw new ParserException(String.Format("Custom template \"{0}\" is not defined", templateName), Line, Column); TemplateStatement tmp = context.Templates[templateName]; // create template-specific context TemplateContext tmpContext = new TemplateContext(); tmpContext.ParentContext = context; tmpContext.Templates = context.Templates; // evaluate inner statements StringWriter innerWriter = new StringWriter(); foreach (Statement stm in Statements) stm.Eval(context, innerWriter); tmpContext.Variables["innerText"] = innerWriter.ToString(); // set context variables foreach (string name in parameters.Keys) tmpContext.Variables[name] = parameters[name].Eval(context); // evaluate template statements foreach (Statement stm in tmp.Statements) stm.Eval(tmpContext, writer); }
public void It_Should_Allow_Variables_In_Args() { // Arrange const string templateString = "Result : {% tablerow i in array cols: x limit: y offset: z %}{{ i }}{% endtablerow %}"; TemplateContext ctx = new TemplateContext(); ctx.DefineLocalVariable("array", new ArrayValue(new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 }.Select(x => (IExpressionConstant)NumericValue.Create(x)).ToList()) ); ctx.DefineLocalVariable("x", NumericValue.Create(2)); ctx.DefineLocalVariable("y", NumericValue.Create(3)); ctx.DefineLocalVariable("z", NumericValue.Create(1)); var template = LiquidTemplate.Create(templateString); // Act String result = template.Render(ctx); Logger.Log(result); // Assert Assert.That(result, Is.StringContaining("<tr class=\"row1\">")); Assert.That(result, Is.StringContaining("<tr class=\"row2\">")); Assert.That(result, Is.Not.StringContaining("<tr class=\"row3\">")); Assert.That(result, Is.Not.StringContaining(">1</td>")); Assert.That(result, Is.StringContaining(">2</td>")); Assert.That(result, Is.StringContaining(">4</td>")); Assert.That(result, Is.Not.StringContaining(">5</td>")); }
public void It_Should_Parse_Includes() { DateTime start = DateTime.Now; // Arrange int includes = 100; //String templateFragment = "{% for i in (1..10) %}{{ array[i] }}"; String template = "<html><body>\r\n"; for (int i = 0; i < includes; i++) { template += "{% include \"test" + i + "\" %}"; } var virtualFs = Enumerable.Range(1, includes).ToDictionary(k => "test" + k.ToString(), CreateInclude); template += "</body>\r\n</html>"; ITemplateContext ctx = new TemplateContext() .WithAllFilters() .WithFileSystem(new TestFileSystem(virtualFs)) .DefineLocalVariable("array", CreateArrayValues()); // Act var result = RenderingHelper.RenderTemplate(template, ctx); //Logger.Log(result); // Assert var end = DateTime.Now; TimeSpan timeDiff = end - start; Logger.Log("ELAPSED: " + timeDiff.TotalMilliseconds); Assert.That(timeDiff.Milliseconds < 500); //Assert.Fail("Not Implemented Yet"); }
/// <summary> /// 解析标签 /// </summary> /// <param name="context">上下文</param> public override Object Parse(TemplateContext context) { using (System.IO.StringWriter write = new System.IO.StringWriter()) { Excute(Source.Parse(context), context, write); return write.ToString(); } }
protected virtual void Apply(TemplateContext ctx) { ctx.CurrentProperty.GetStatements._("return {0}", Field.Name); if (!ManualSetter) ctx.CurrentProperty.SetStatements._("{0} = value", Field.Name); if (DefaultExpression != null) Field.InitExpression = new CodeSnippetExpression(DefaultExpression); }
/// <summary> /// 解析标签 /// </summary> /// <param name="context">上下文</param> public override object Parse(TemplateContext context) { if(context.StripWhiteSpace) { return (this.ToString() ?? string.Empty).Trim(); } return this.ToString(); }
/// <summary> /// Substracts from the input value the `with` value /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="value">The input value</param> /// <param name="with">The with value to substract from `value`</param> /// <returns>The results of the substraction: `value` - `with`</returns> /// <remarks> /// ```scriban-html /// {{ 255 | math.minus 5}} /// ``` /// ```html /// 250 /// ``` /// </remarks> public static object Minus(TemplateContext context, SourceSpan span, object value, object with) { return(ScriptBinaryExpression.Evaluate(context, span, ScriptBinaryOperator.Substract, value, with)); }
public static ValueTask <Completion> WriteToAsync(TextWriter writer, TextEncoder encoder, TemplateContext context) { var services = ((LiquidTemplateContext)context).Services; var antiforgery = services.GetRequiredService <IAntiforgery>(); var httpContextAccessor = services.GetRequiredService <IHttpContextAccessor>(); var httpContext = httpContextAccessor.HttpContext; var tokenSet = antiforgery.GetAndStoreTokens(httpContext); writer.Write("<input name=\""); writer.Write(encoder.Encode(tokenSet.FormFieldName)); writer.Write("\" type=\"hidden\" value=\""); writer.Write(encoder.Encode(tokenSet.RequestToken)); writer.Write("\" />"); return(new ValueTask <Completion>(Completion.Normal)); }
public static async ValueTask <FluidValue> Map(FluidValue input, FilterArguments arguments, TemplateContext context) { if (input.Type != FluidValues.Array) { return(input); } var member = arguments.At(0).ToStringValue(); var list = new List <FluidValue>(); foreach (var item in input.Enumerate(context)) { list.Add(await item.GetValueAsync(member, context)); } return(new ArrayValue(list)); }
public async ValueTask <FluidValue> ProcessAsync(FluidValue input, FilterArguments arguments, TemplateContext ctx) { if (!ctx.AmbientValues.TryGetValue("Services", out var services)) { throw new ArgumentException("Services missing while invoking 'inherited_terms'"); } ContentItem taxonomy = null; string termContentItemId = null; var contentManager = ((IServiceProvider)services).GetRequiredService <IContentManager>(); if (input.Type == FluidValues.Object && input.ToObjectValue() is ContentItem term) { termContentItemId = term.ContentItemId; } else { termContentItemId = input.ToStringValue(); } var firstArg = arguments.At(0); if (firstArg.Type == FluidValues.Object && input.ToObjectValue() is ContentItem contentItem) { taxonomy = contentItem; } else { taxonomy = await contentManager.GetAsync(firstArg.ToStringValue()); } if (taxonomy == null) { return(null); } var terms = new List <ContentItem>(); TaxonomyOrchardHelperExtensions.FindTermHierarchy(taxonomy.Content.TaxonomyPart.Terms as JArray, termContentItemId, terms); return(FluidValue.Create(terms)); }
public abstract Task <Completion> WriteToAsync(TextWriter writer, TextEncoder encoder, TemplateContext context, List <Statement> statements);
private void Dispatch(TemplateContext tc, string line) { int i = 0; while (i < line.Length) { // コメント if (string.Compare(line, i, m_commentbegin, 0, m_commentbegin.Length, StringComparison.OrdinalIgnoreCase) == 0) { i = Skip(line, i + m_commentbegin.Length, m_commentbegin, m_commentend); continue; } // テンプレートコマンドの展開 if (string.Compare(line, i, m_commandprefix, 0, m_commandprefix.Length, StringComparison.OrdinalIgnoreCase) == 0) { int endpos = line.IndexOf(m_commandpostfix, i + m_commandprefix.Length); if (endpos > 0) { string[] cmdparam = line.Substring(i + m_commandprefix.Length, endpos - i - m_commandprefix.Length).Trim().Split(" \t".ToCharArray(), 2); Command cmd = null; foreach (KeyValuePair <string, object> kv in m_command) { if (kv.Key == cmdparam[0].ToLower()) { cmd = (Command)kv.Value; break; } } if (cmd != null) { i = cmd(line, endpos + m_commandpostfix.Length, tc, cmdparam[0], (cmdparam.Length > 1)?cmdparam[1].Trim():""); continue; } else { LOG_ERR(string.Format("Unknown template command '{0}{1}{2}'", m_commandprefix, cmdparam[0], m_commandpostfix)); } } } // テンプレート変数の展開 if (string.Compare(line, i, m_prefix, 0, m_prefix.Length, StringComparison.OrdinalIgnoreCase) == 0) { int endpos = line.IndexOf(m_postfix, i + m_prefix.Length); if (endpos > 0) { string val = GetVariableValue(tc.dict, line.Substring(i + m_prefix.Length, endpos - i - m_prefix.Length)); if (val != null) { tc.sb.Append(val); i = endpos + m_postfix.Length; continue; } } } // 一文字出力 tc.sb.Append(line[i]); i++; } }
public override void Eval(TemplateContext context, System.IO.StringWriter writer) { writer.Write(PrintExpression.Eval(context)); }
public static async ValueTask <FluidValue> SortNatural(FluidValue input, FilterArguments arguments, TemplateContext context) { if (arguments.Count > 0) { var member = arguments.At(0).ToStringValue(); var values = new List <KeyValuePair <FluidValue, object> >(); foreach (var item in input.Enumerate(context)) { values.Add(new KeyValuePair <FluidValue, object>(item, (await item.GetValueAsync(member, context)).ToObjectValue())); } var orderedValues = values .OrderBy(x => x.Value) .Select(x => x.Key) .ToArray(); return(new ArrayValue(orderedValues)); } else { return(new ArrayValue(input.Enumerate(context).OrderBy(x => x.ToStringValue(), StringComparer.OrdinalIgnoreCase))); } }
// https://github.com/Shopify/liquid/commit/842986a9721de11e71387732be51951285225977 public static async ValueTask <FluidValue> Where(FluidValue input, FilterArguments arguments, TemplateContext context) { if (input.Type != FluidValues.Array) { return(input); } // First argument is the property name to match var member = arguments.At(0).ToStringValue(); // Second argument is the value to match, or 'true' if none is defined var targetValue = arguments.At(1).Or(BooleanValue.True); var list = new List <FluidValue>(); foreach (var item in input.Enumerate(context)) { var itemValue = await item.GetValueAsync(member, context); if (itemValue.Equals(targetValue)) { list.Add(item); } } return(new ArrayValue(list)); }
public static ValueTask <FluidValue> Join(FluidValue input, FilterArguments arguments, TemplateContext context) { if (input.Type != FluidValues.Array) { return(input); } var separator = arguments.At(0).ToStringValue(); var values = input.Enumerate(context).Select(x => x.ToStringValue()); var joined = string.Join(separator, values); return(new StringValue(joined)); }
public static ValueTask <FluidValue> Uniq(FluidValue input, FilterArguments arguments, TemplateContext context) { return(new ArrayValue(input.Enumerate(context).Distinct().ToArray())); }
public static FluidValue Strip(FluidValue input, FilterArguments arguments, TemplateContext context) { return(new StringValue(input.ToStringValue().Trim())); }
public static FluidValue Replace(FluidValue input, FilterArguments arguments, TemplateContext context) { return(new StringValue(input.ToStringValue().Replace(arguments.At(0).ToStringValue(), arguments.At(1).ToStringValue()))); }
public static FluidValue ReplaceFirst(FluidValue input, FilterArguments arguments, TemplateContext context) { string remove = arguments.At(0).ToStringValue(); var value = input.ToStringValue(); var index = value.IndexOf(remove); if (index != -1) { return(new StringValue(value.Substring(0, index) + arguments.At(1).ToStringValue() + value.Substring(index + remove.Length))); } return(input); }
private int CommandEnddef(string line, int index, TemplateContext tc, string commandname, string param) { LOG_ERR(string.Format("Error: Mismatched {0} directive.", commandname)); return(index); }
public override ValueTask <Completion> WriteToAsync(TextWriter writer, TextEncoder encoder, TemplateContext context) { return(_writeAsync(writer, encoder, context)); }
private int CommandFor(string line, int index, TemplateContext tc, string commandname, string param) { string contents; index = Capture(line, index, m_commandprefix + commandname, m_commandprefix + "end" + commandname + m_commandpostfix, out contents); ObjectDictionary args = ObjectDictionary.FromString(param); string variable = null; if (args.ContainsKey("0")) { variable = args["0"].ToString(); } else if (args.ContainsKey("var")) { variable = args["var"].ToString(); } string list = null; if (args.ContainsKey("1") && (args["1"].ToString() == "in") && args.ContainsKey("2")) { list = args["2"].ToString(); } else if (args.ContainsKey("list")) { list = args["list"].ToString(); } string countvar = null; if (args.ContainsKey("count")) { countvar = args["count"].ToString(); } int countstart = 1; if (args.ContainsKey("countstart")) { object countstartobj = tc.dict.GetObject(args["countstart"].ToString()); if (countstartobj != null) { countstart = StringUtil.ToInt(countstartobj.ToString(), countstart); } } string indexvar = null; if (args.ContainsKey("index")) { indexvar = args["index"].ToString(); } string evenvar = null; if (args.ContainsKey("even")) { evenvar = args["even"].ToString(); } string oddvar = null; if (args.ContainsKey("odd")) { oddvar = args["odd"].ToString(); } if (string.IsNullOrEmpty(variable) || string.IsNullOrEmpty(list)) { LOG_ERR(string.Format("Error: Invalid syntax, should be '{0}{1} var-name in list-variable {2}'", m_commandprefix, commandname, m_commandpostfix)); return(index); } object listobj = tc.dict.GetObject(list); if (listobj == null) { LOG_ERR(string.Format("Error: Object {0} is not assigned.", list)); return(index); } if (!(listobj is IEnumerable)) { LOG_ERR(string.Format("Error: Object {0} is not an Enumerable.", list)); return(index); } TemplateContext innertc = new TemplateContext(tc.sb, tc.dict); int i = 0; foreach (object obj in (listobj as IEnumerable)) { innertc.dict[variable] = obj; if (!String.IsNullOrEmpty(countvar)) { innertc.dict[countvar] = i + countstart; } if (!String.IsNullOrEmpty(indexvar)) { innertc.dict[indexvar] = i; } if (!String.IsNullOrEmpty(evenvar)) { innertc.dict[evenvar] = ((i % 2) == 0); } if (!String.IsNullOrEmpty(oddvar)) { innertc.dict[oddvar] = ((i % 2) == 1); } Dispatch(innertc, contents); i++; } return(index); }
public SalaryRepository(IOptions <Settings> settings) { _context = new TemplateContext(settings); }
public async ValueTask <FluidValue> ProcessAsync(FluidValue input, FilterArguments arguments, TemplateContext ctx) { if (!ctx.AmbientValues.TryGetValue("Services", out var services)) { throw new ArgumentException("Services missing while invoking 'github_issue'"); } var gitHubApiService = ((IServiceProvider)services).GetRequiredService <IGitHubApiService>(); var owner = arguments["owner"].Or(arguments.At(0)).ToStringValue(); var repo = arguments["repository"].Or(arguments.At(1)).ToStringValue(); var tokenName = arguments["tokenName"].Or(arguments.At(2)).ToStringValue(); var prNumber = input.ToStringValue(); if (string.IsNullOrEmpty(owner) || string.IsNullOrEmpty(repo)) { throw new ArgumentException("Missing owner, repository or tokenName while invoking 'github_issue'"); } if (!int.TryParse(prNumber, out var parsedNumber)) { throw new ArgumentException("Please provide a valid issue number while invoking 'github_issue'"); } try { var client = await gitHubApiService.GetGitHubClient(tokenName); return(FluidValue.Create(await client.Issue.Get(owner, repo, parsedNumber))); } catch (Octokit.ApiException ex) { return(FluidValue.Create(ex.Message)); } }
public override void Eval(TemplateContext context, System.IO.StringWriter writer) { context.Variables[Name] = ValueExpression.Eval(context); }
public ValueTask <FluidValue> ProcessAsync(FluidValue input, FilterArguments arguments, TemplateContext context) { return(new ValueTask <FluidValue>(new ObjectValue(JObject.Parse(input.ToStringValue())))); }
public void TestFrontMatterOnly() { var options = new ParserOptions(); var input = @"+++ variable = 1 name = 'yes' +++ This is after the frontmatter: {{ name }} {{ variable + 1 }}"; input = input.Replace("\r\n", "\n"); var lexer = new Lexer(input, null, new LexerOptions() { Mode = ScriptMode.FrontMatterOnly }); var parser = new Parser(lexer, options); var page = parser.Run(); foreach (var message in parser.Messages) { Console.WriteLine(message); } Assert.False(parser.HasErrors); // Check that the parser finished parsing on the first code exit }} // and hasn't tried to run the lexer on the remaining text Assert.AreEqual(new TextPosition(34, 4, 0), parser.CurrentSpan.Start); var startPositionAfterFrontMatter = page.FrontMatter.TextPositionAfterEndMarker; // Make sure that we have a front matter Assert.NotNull(page.FrontMatter); Assert.Null(page.Body); var context = new TemplateContext(); // Evaluate front-matter var frontResult = context.Evaluate(page.FrontMatter); Assert.Null(frontResult); lexer = new Lexer(input, null, new LexerOptions() { StartPosition = startPositionAfterFrontMatter }); parser = new Parser(lexer); page = parser.Run(); foreach (var message in parser.Messages) { Console.WriteLine(message); } Assert.False(parser.HasErrors); context.Evaluate(page); var pageResult = context.Output.ToString(); TextAssert.AreEqual("This is after the frontmatter: yes\n2", pageResult); }
/// <summary> /// 获取布布值 /// </summary> /// <param name="context">上下文</param> public override Boolean ToBoolean(TemplateContext context) { return(this._test.ToBoolean(context)); }
public static ValueTask <FluidValue> Last(FluidValue input, FilterArguments arguments, TemplateContext context) { return(input.GetValueAsync("last", context)); }
public override async Task <Completion> WriteToAsync(TextWriter writer, TextEncoder encoder, TemplateContext context, FilterArgument[] args) { if (!context.AmbientValues.TryGetValue("ThemeLayout", out dynamic layout)) { throw new ArgumentException("ThemeLayout missing while invoking 'render_section'"); } if (!context.AmbientValues.TryGetValue("DisplayHelper", out dynamic displayHelper)) { throw new ArgumentException("DisplayHelper missing while invoking 'render_section'"); } var arguments = (FilterArguments)(await new ArgumentsExpression(args).EvaluateAsync(context)).ToObjectValue(); var name = arguments.At(0).ToStringValue(); var required = arguments.HasNamed("required") ? Convert.ToBoolean(arguments["required"].ToStringValue()) : false; var zone = layout[name]; if (required && zone != null && zone.Items.Count == 0) { throw new InvalidOperationException("Zone not found while invoking 'render_section': " + name); } var htmlContent = await(Task <IHtmlContent>) displayHelper(zone); htmlContent.WriteTo(writer, HtmlEncoder.Default); return(Completion.Normal); }
public PhoneRepository(TemplateContext context) : base(context) { }
public override Boolean ToBoolean(TemplateContext context) { return(this.Value); }
/// <summary> /// Performs the multiplication of the input value with the `with` value /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="value">The input value</param> /// <param name="with">The with value to multiply to`value`</param> /// <returns>The results of the multiplication: `value` * `with`</returns> /// <remarks> /// ```scriban-html /// {{ 2 | math.times 3}} /// ``` /// ```html /// 6 /// ``` /// </remarks> public static object Times(TemplateContext context, SourceSpan span, object value, object with) { return(ScriptBinaryExpression.Evaluate(context, span, ScriptBinaryOperator.Multiply, value, with)); }
public static ValueTask <FluidValue> Reverse(FluidValue input, FilterArguments arguments, TemplateContext context) { if (input.Type == FluidValues.Array) { return(new ArrayValue(input.Enumerate(context).Reverse())); } else if (input.Type == FluidValues.String) { var value = input.ToStringValue(); if (String.IsNullOrEmpty(value)) { return(StringValue.Empty); } else { var valueAsArray = value.ToCharArray(); Array.Reverse(valueAsArray); return(new ArrayValue(valueAsArray.Select(e => new StringValue(e.ToString())))); } } else { return(input); } }
public static ValueTask <FluidValue> Concat(FluidValue input, FilterArguments arguments, TemplateContext context) { if (input.Type != FluidValues.Array) { return(input); } if (arguments.At(0).Type != FluidValues.Array) { return(input); } var concat = new List <FluidValue>(); foreach (var item in input.Enumerate(context)) { concat.Add(item); } foreach (var item in arguments.At(0).Enumerate(context)) { concat.Add(item); } return(new ArrayValue(concat)); }