//public IExpressionConstant Eval(SymbolTableStack symbolTableStack, IEnumerable<IExpressionConstant> expressions) public override LiquidExpressionResult Eval(ITemplateContext templateContext, IEnumerable<Option<IExpressionConstant>> expressions) { //IList<IExpressionConstant> exprList = expressions.ToList(); IList<Option<IExpressionConstant>> exprList = expressions.ToList(); //Console.WriteLine("EqualsExpression is Eval-ing expressions "); if (exprList.Count() != 2) { //return LiquidExpressionResult.Error("Equals is a binary expression but received " + exprList.Count() + "."); return LiquidExpressionResult.Error("Equals is a binary expression but received " + exprList.Count() + "."); } if (exprList.All(x => !x.HasValue)) // both null { return LiquidExpressionResult.Success(new BooleanValue(false)); } if (exprList.Any(x => !x.HasValue)) // one null { return LiquidExpressionResult.Success(new BooleanValue(true)); } if (exprList[0].GetType() == exprList[1].GetType()) { return LiquidExpressionResult.Success(new BooleanValue(! exprList[0].Value.Equals(exprList[1].Value))); } return LiquidExpressionResult.Error("\"Not Equals\" implementation can't cast yet"); }
public LiquidString Render( RenderingVisitor renderingVisitor, MacroBlockTag macroBlocktag, ITemplateContext templateContext, IList <Option <ILiquidValue> > args) { var macroScope = new SymbolTable(); var i = 0; foreach (var varName in macroBlocktag.Args.Take(args.Count)) { macroScope.DefineLocalVariable(varName, args[i]); i++; } templateContext.SymbolTableStack.Push(macroScope); String hiddenText = ""; renderingVisitor.PushTextAccumulator(str => hiddenText += str); renderingVisitor.StartWalking(macroBlocktag.LiquidBlock); renderingVisitor.PopTextAccumulator(); templateContext.SymbolTableStack.Pop(); return(LiquidString.Create(hiddenText)); }
/// <summary> /// Look up the index in the value. This works for dictionaries, arrays and strings. /// </summary> /// <param name="ctx"></param> /// <param name="value"></param> /// <param name="indexProperty"></param> /// <returns></returns> public LiquidExpressionResult Lookup( ITemplateContext ctx, ILiquidValue value, ILiquidValue indexProperty) { var arr = value as LiquidCollection; if (arr != null) { return(DoLookup(ctx, arr, indexProperty)); } var dict = value as LiquidHash; if (dict != null) { return(DoLookup(ctx, dict, indexProperty)); } var str = value as LiquidString; if (str != null) { return(DoLookup(ctx, str, indexProperty)); } return(LiquidExpressionResult.Error("ERROR : cannot apply an index to a " + value.LiquidTypeName + ".")); }
private static TemplateContext.CopyIndexState[] GetVariableIterator(ITemplateContext context, JObject value) { if (value.ContainsKey(PROPERTY_COPY)) { var result = new List <TemplateContext.CopyIndexState>(); var copyObjectArray = value[PROPERTY_COPY].Value <JArray>(); for (var i = 0; i < copyObjectArray.Count; i++) { var copyObject = copyObjectArray[i] as JObject; var state = new TemplateContext.CopyIndexState(); state.Name = ExpandProperty <string>(context, copyObject, PROPERTY_NAME); state.Input = copyObject[PROPERTY_INPUT]; state.Count = ExpandPropertyInt(context, copyObject, PROPERTY_COUNT); context.CopyIndex.Push(state); value.Remove(PROPERTY_COPY); result.Add(state); } return(result.ToArray()); } else { return new TemplateContext.CopyIndexState[] { new TemplateContext.CopyIndexState { Input = value } } }; }
public override ValueExpression Evaluate(ITemplateContext context) { ValueExpression value = _value.Evaluate(context); if (value.Type == typeof(int)) { return(Expression.Value(~(int)value.Value)); } if (value.Type == typeof(uint)) { return(Expression.Value(~(uint)value.Value)); } if (value.Type == typeof(long)) { return(Expression.Value(~(long)value.Value)); } if (value.Type == typeof(ulong)) { return(Expression.Value(~(ulong)value.Value)); } throw new OverflowException(); }
private static JToken ExpandObject(ITemplateContext context, JObject obj) { foreach (var copyIndex in GetPropertyIterator(context, obj)) { if (copyIndex.IsCopy()) { var array = new JArray(); while (copyIndex.Next()) { var instance = copyIndex.CloneInput <JToken>(); array.Add(ResolveToken(context, instance)); } obj[copyIndex.Name] = array; context.CopyIndex.Pop(); } else { foreach (var property in obj.Properties()) { ResolveProperty(context, obj, property.Name); } } } return(obj); }
public override LiquidExpressionResult Apply(ITemplateContext ctx, LiquidString liquidLiquidStringExpression) { return(LiquidExpressionResult.Success(LiquidString.Create( (liquidLiquidStringExpression == null ? "NULL" : liquidLiquidStringExpression.StringVal) + " " + (LiquidStringArg1 == null ? "NULL" : LiquidStringArg1.StringVal) + " " + (LiquidStringArg2 == null ? "NULL" : LiquidStringArg2.StringVal)))); }
public override LiquidExpressionResult Eval(ITemplateContext templateContext, IEnumerable<Option<IExpressionConstant>> expressions) { IList<Option<IExpressionConstant>> exprList = expressions.ToList(); if (exprList.Count() != 2) { // This shouldn't happen if the parser is correct. return LiquidExpressionResult.Error("Equals is a binary expression but received " + exprList.Count() + "."); } if (!exprList[0].HasValue && !exprList[1].HasValue) { return LiquidExpressionResult.Success(new BooleanValue(true)); } if (!exprList[0].HasValue || !exprList[1].HasValue) { return LiquidExpressionResult.Success(new BooleanValue(false)); } if (exprList[0].GetType() == exprList[1].GetType()) { var isEqual = exprList[0].Value.Equals(exprList[1].Value); return LiquidExpressionResult.Success(new BooleanValue(isEqual)); } return LiquidExpressionResult.Error("\"Equals\" implementation can't cast that yet"); }
private static object Index(ITemplateContext context, ExpressionFnOuter inner, ExpressionFnOuter index) { var source = inner(context); var indexResult = index(context); if (source is JArray jArray && ExpressionHelpers.TryConvertInt(indexResult, out int arrayIndex)) { return(jArray[arrayIndex]); } if (source is JObject jObject && ExpressionHelpers.TryString(indexResult, out string propertyName)) { var property = jObject[propertyName]; if (property == null) { throw new ExpressionReferenceException(propertyName, string.Format(Thread.CurrentThread.CurrentCulture, PSRuleResources.PropertyNotFound, propertyName)); } return(property); } if (source is MockNode mockNode && ExpressionHelpers.TryConvertString(indexResult, out string memberName)) { return(mockNode.GetMember(memberName)); } throw new InvalidOperationException(string.Format(Thread.CurrentThread.CurrentCulture, PSRuleResources.IndexInvalid, indexResult)); }
public override LiquidExpressionResult ApplyTo(ITemplateContext ctx, LiquidRange liquidGeneratorExpression) { //return GetSize(liquidGeneratorExpression, () => LiquidNumeric.Create(liquidGeneratorExpression.Length)); return(liquidGeneratorExpression == null ? SizeOfNil() : LiquidExpressionResult.Success(LiquidNumeric.Create(liquidGeneratorExpression.Length))); }
public string Render(IExpressionParser parser, ITemplateContext context) { StringBuilder output = new StringBuilder(); this.Render(parser, context, output); return(output.ToString()); }
public override LiquidExpressionResult Eval(ITemplateContext templateContext, IEnumerable <Option <ILiquidValue> > expressions) { IList <Option <ILiquidValue> > exprList = expressions.ToList(); if (exprList.Count != 2) { return(LiquidExpressionResult.Error("Contains is a binary expression but received " + exprList.Count + ".")); } if (!exprList[0].HasValue || !exprList[1].HasValue) { return(LiquidExpressionResult.Success(new LiquidBoolean(false))); } //return Contains((dynamic) exprList[0].Value, exprList[1].Value); var arr = exprList[0].Value as LiquidCollection; if (arr != null) { return(Contains(arr, exprList[1].Value)); } var dict = exprList[0].Value as LiquidHash; if (dict != null) { return(Contains(dict, exprList[1].Value)); } var str = exprList[0].Value as LiquidString; if (str != null) { return(Contains(str, exprList[1].Value)); } return(Contains(exprList[0].Value, exprList[1].Value)); }
internal TemplateVisitor(ITemplateContext ctx, ExpressionLanguageEngineConfig cfg) { _ctx = ctx; _engine = ExpressionLanguageEngine.CreateEngine(cfg, _ctx); _str = new StringBuilder(); }
/// <summary> /// Look up the index in the value. This works for dictionaries, arrays and strings. /// </summary> /// <param name="ctx"></param> /// <param name="value"></param> /// <param name="indexProperty"></param> /// <returns></returns> public LiquidExpressionResult Lookup( ITemplateContext ctx, IExpressionConstant value, IExpressionConstant indexProperty) { //Console.WriteLine("LOOKUP=> VALUE: " + value); //Console.WriteLine(" => INDEX: " + indexProperty); if (value == null) { return LiquidExpressionResult.Error("ERROR : cannot apply an index to a nil value."); } //return DoLookup(ctx, (dynamic) value, indexProperty); var arr = value as ArrayValue; if (arr != null) { return DoLookup(ctx, arr, indexProperty); } var dict = value as DictionaryValue; if (dict != null) { return DoLookup(ctx, dict, indexProperty); } var str = value as StringValue; if (str != null) { return DoLookup(ctx, str, indexProperty); } return LiquidExpressionResult.Error("ERROR : cannot apply an index to a " + value.LiquidTypeName + "."); }
private static void RenderPreviewMode(ITemplateContext context, string name) { switch (name) { case "Email": context.Write("*****@*****.**"); break; case "ID": context.Write("xxxxxxxxx"); break; case "Name": context.Write("User Name"); break; case "FirstName": context.Write("FirstName"); break; case "LastName": context.Write("LastName"); break; } }
/// <summary> /// this calls the renderer with the astRenderer to render /// the block. /// </summary> public void Render(ForBlockTag forBlockTag, ITemplateContext templateContext) { var localBlockScope = new SymbolTable(); templateContext.SymbolTableStack.Push(localBlockScope); try { var iterableFactory = forBlockTag.IterableCreator; // TODO: the Eval may result in an LiquidCollection with no Array // (i.e. it's undefined). THe ToList therefore fails.... // this should use Bind var iterable = iterableFactory.Eval(templateContext).ToList(); if (forBlockTag.Reversed.BoolValue) { iterable.Reverse(); // stupid thing does it in-place. } IterateBlock(forBlockTag, templateContext, iterable); } finally { templateContext.SymbolTableStack.Pop(); } }
public override LiquidExpressionResult Eval(ITemplateContext templateContext, IEnumerable<Option<IExpressionConstant>> expressions) { IList<Option<IExpressionConstant>> exprList = expressions.ToList(); if (exprList.Count() != 2) { //return LiquidExpressionResult.Error("Contains is a binary expression but received " + exprList.Count() + "."); return LiquidExpressionResult.Error("Contains is a binary expression but received " + exprList.Count() + "."); } if (!exprList[0].HasValue || !exprList[1].HasValue) { return LiquidExpressionResult.Success(new BooleanValue(false)); } //return Contains((dynamic) exprList[0].Value, exprList[1].Value); var arr = exprList[0].Value as ArrayValue; if (arr != null) { return Contains(arr, exprList[1].Value); } var dict = exprList[0].Value as DictionaryValue; if (dict != null) { return Contains(dict, exprList[1].Value); } var str = exprList[0].Value as StringValue; if (str != null) { return Contains(str, exprList[1].Value); } return Contains(exprList[0].Value, exprList[1].Value); }
public void Render(IncludeTag includeTag, ITemplateContext templateContext) { if (templateContext.FileSystem == null) { AddRenderingErrorToResult(new LiquidError { Message = " ERROR: FileSystem is not defined" }); return; } String virtualFileName = null; LiquidExpressionEvaluator.Eval(includeTag.VirtualFileExpression, templateContext) .WhenError(AddRenderingErrorToResult) .WhenSuccess(result => { virtualFileName = ValueCaster.RenderAsString(result); }); if (virtualFileName == null) { return; } //virtualFileName = ValueCaster.RenderAsString(virtualFilenameVar.SuccessResult.Value); String snippet = templateContext.FileSystem.Include(templateContext, virtualFileName); templateContext.SymbolTableStack.DefineLocalRegistry(LOCALREGISTRY_FILE_KEY, virtualFileName); RenderSnippet(includeTag, templateContext, snippet, virtualFileName); }
public override LiquidExpressionResult Eval(ITemplateContext templateContext, IEnumerable<Option<IExpressionConstant>> expressions) { //_variableReference.Eval(symbolTableStack, new List<IExpressionConstant>()) var liquidExpressionResult = _variableReference.Eval(templateContext, new List<Option<IExpressionConstant>>()); if (liquidExpressionResult.IsError) { return liquidExpressionResult; } if (!liquidExpressionResult.SuccessResult.HasValue) { return LiquidExpressionResult.Success(Option<IExpressionConstant>.None()); ; // no dictionary to look up in } var dict = liquidExpressionResult.SuccessResult.Value as DictionaryValue; if (dict != null) { return LiquidExpressionResult.Success(dict.ValueAt(Convert.ToString(_index))); } return LiquidExpressionResult.Success(Option<IExpressionConstant>.None()); // // TODO: Implement the rest of this // return new Undefined(_variableReference +"." + _index); }
object Read(ITemplateContext context, string nm) { if (string.IsNullOrEmpty(nm)) { return(null); } object obj = null; if (context.TryGetValue(nm, out obj) && null != obj) { return(obj); } string[] names = nm.Split('.'); if (1 == names.Length) { return(null); } obj = context; foreach (string name in names) { obj = Read(obj, name, names); if (null == obj) { return(null); } } return(obj); }
public override LiquidExpressionResult ApplyTo(ITemplateContext ctx, ILiquidValue liquidExpression) { var strArray = ValueCaster.RenderAsString(liquidExpression).Split(); // TODO: add ability to toggle lower-case on/off return(LiquidExpressionResult.Success(StringUtils.Eval(liquidExpression, x => Slug.Create(true, strArray)))); }
private ExpandedObject Build(ITemplateContext context) { IDictionary <string, object> dictionary = new ExpandedObject(); var serializer = Container.Get <IJsonSerializer>(); foreach (var property in this.properties) { if (this.jsonKeys.Contains(property.Key)) { string values = property.Value.ToString(); string value = MarkerRegex.Replace( values, m => { string propertyName = m.Groups[1].Value; object retValue = context.GetValue(propertyName); return(retValue == null ? string.Empty : retValue.ToString()); }); var parsedValue = serializer.Deserialize <object>(value); dictionary.Add(property.Key, parsedValue); } else { dictionary.Add(property.Key, property.Value); } } return((ExpandedObject)dictionary); }
public void Render(IExpressionParser parser, ITemplateContext context, StringBuilder output) { foreach (TokenNode node in this.ChildNodes) { node.Evaluate(parser, context, output); } }
private void GetDiscoveryConfig(ITemplateContext templateContext, TemplateInputConfig templateConfig) { foreach (var discovery in SDKHelper.GetFolderItems <ManagementPackDiscovery>(this, templateContext.OutputFolder)) { var discoveryConfig = discovery.DataSource.Configuration; if (discovery.Name.StartsWith(ClustersDiscoveryNamePrefix, StringComparison.OrdinalIgnoreCase)) { if (WatcherNodesListNodeRegex.IsMatch(discoveryConfig)) { templateConfig.WatcherNodesList = WatcherNodesListNodeRegex.Match(discoveryConfig).Groups[1].Value; } } else if (discovery.Name.StartsWith(SeedDiscoveryNamePrefix, StringComparison.OrdinalIgnoreCase)) { if (SeedComputerNameNodeRegex.IsMatch(discoveryConfig)) { templateConfig.SeedComputerName = SeedComputerNameNodeRegex.Match(discoveryConfig).Groups[1].Value; } if (AmbariUriNodeRegex.IsMatch(discoveryConfig)) { templateConfig.AmbariUri = AmbariUriNodeRegex.Match(discoveryConfig).Groups[1].Value; } } } }
public override LiquidExpressionResult Eval(ITemplateContext templateContext, IEnumerable <Option <ILiquidValue> > expressions) { IList <Option <ILiquidValue> > exprList = expressions.ToList(); if (exprList.Count != 2) { // This shouldn't happen if the parser is correct. return(LiquidExpressionResult.Error("Equals is a binary expression but received " + exprList.Count + ".")); } if (!exprList[0].HasValue && !exprList[1].HasValue) { return(LiquidExpressionResult.Success(new LiquidBoolean(true))); } if (!exprList[0].HasValue || !exprList[1].HasValue) { return(LiquidExpressionResult.Success(new LiquidBoolean(false))); } if (exprList[0].GetType() == exprList[1].GetType()) { var isEqual = exprList[0].Value.Equals(exprList[1].Value); return(LiquidExpressionResult.Success(new LiquidBoolean(isEqual))); } return(LiquidExpressionResult.Error("\"Equals\" implementation can't cast that yet")); }
// public override void Accept(IExpressionDescriptionVisitor expressionDescriptionVisitor) // { // expressionDescriptionVisitor.Visit(this); // } //public ILiquidValue Eval(SymbolTableStack symbolTableStack, IEnumerable<ILiquidValue> expressions) public override LiquidExpressionResult Eval(ITemplateContext templateContext, IEnumerable <Option <ILiquidValue> > expressions) { //IList<ILiquidValue> exprList = expressions.ToList(); IList <Option <ILiquidValue> > exprList = expressions.ToList(); //Console.WriteLine("EqualsExpression is Eval-ing expressions "); if (exprList.Count != 2) { //return LiquidExpressionResult.Error("Equals is a binary expression but received " + exprList.Count() + "."); return(LiquidExpressionResult.Error("Equals is a binary expression but received " + exprList.Count + ".")); } if (exprList.All(x => !x.HasValue)) // both null { return(LiquidExpressionResult.Success(new LiquidBoolean(false))); } if (exprList.Any(x => !x.HasValue)) // one null { return(LiquidExpressionResult.Success(new LiquidBoolean(true))); } if (exprList[0].GetType() == exprList[1].GetType()) { return(LiquidExpressionResult.Success(new LiquidBoolean(!exprList[0].Value.Equals(exprList[1].Value)))); } return(LiquidExpressionResult.Error("\"Not Equals\" implementation can't cast yet")); }
public override ValueExpression Evaluate(ITemplateContext context) { ClassName className = _TypeExpression.Evaluate(context).Value as ClassName; if (className == null) { throw new Exception("as operator requires type"); } Type checkType = className.Type; ValueExpression objectValue = _ObjectExpression.Evaluate(context); Type objectType = objectValue.Type; if (objectValue.Value == null) { return(Expression.Value(null, checkType)); } objectType = Nullable.GetUnderlyingType(objectType) ?? objectType; if (!objectType.IsValueType) { return(Expression.Value(objectValue.Value, checkType)); } if ((Nullable.GetUnderlyingType(checkType) ?? checkType) == objectType) { return(Expression.Value(objectValue.Value, checkType)); } return(Expression.Value(null, checkType)); }
public TemplateRepository() { _dbContext = new TemplateContext(); _rdbContext = new ReportItemContext(); _sdbContext = new SortItemContext(); _fdbContext = new FilterItemContext(); }
private static JToken ResolveVariable(ITemplateContext context, JToken value) { if (value is JObject jObject) { foreach (var copyIndex in GetVariableIterator(context, jObject)) { if (copyIndex.IsCopy()) { context.CopyIndex.Push(copyIndex); var jArray = new JArray(); while (copyIndex.Next()) { var instance = copyIndex.CloneInput <JToken>(); jArray.Add(ResolveToken(context, instance)); } jObject[copyIndex.Name] = jArray; context.CopyIndex.Pop(); } } return(ResolveToken(context, jObject)); } else if (value is JArray jArray) { return(ExpandArray(context, jArray)); } else if (value is JToken jToken && jToken.Type == JTokenType.String) { return(ExpandPropertyToken(context, jToken)); } return(value); }
public LiquidString Render( RenderingVisitor renderingVisitor, ITemplateContext templateContext, TreeNode <IASTNode> liquidBlock, IList <Option <ILiquidValue> > args) { var localBlockScope = new SymbolTable(); templateContext.SymbolTableStack.Push(localBlockScope); LiquidString result; try { // normally you would need to verify that arg0 and arg1 exists and are the correct value types. String varname = args[0].Value.ToString(); var iterableFactory = new ArrayValueCreator( new TreeNode <LiquidExpression>( new LiquidExpression { Expression = args[1].Value })); var iterable = iterableFactory.Eval(templateContext).ToList(); result = IterateBlock(renderingVisitor, varname, templateContext, iterable, liquidBlock); } finally { templateContext.SymbolTableStack.Pop(); } return(LiquidString.Create("START CUSTOM FOR LOOP" + result.StringVal + "END CUSTOM FOR LOOP")); }
public override ValueExpression Evaluate(ITemplateContext context) { ValueExpression targetValue = _target.Evaluate(context); Type targetType = targetValue.Type; object targetObject = targetValue.Value; ValueExpression[] parameters = EvaluateExpressionArray(_parameters, context); Type[] parameterTypes = Array.ConvertAll <ValueExpression, Type>(parameters, expr => expr.Type); object[] parameterValues = Array.ConvertAll <ValueExpression, object>(parameters, expr => expr.Value); if (targetType.IsArray) { if (targetType.GetArrayRank() != parameters.Length) { throw new Exception("Array has a different rank. Number of arguments is incorrect"); } Type returnType = targetType.GetElementType(); bool useLong = false; foreach (Type t in parameterTypes) { if (t == typeof(long) || t == typeof(long?)) { useLong = true; } else if (t != typeof(int) & t != typeof(int?) && t != typeof(short) && t != typeof(short?) && t != typeof(ushort) && t != typeof(ushort?)) { throw new ArgumentException(); } } if (useLong) { long[] indexes = new long[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { indexes[i] = Convert.ToInt64(parameterValues[i]); } return(Expression.Value(((Array)targetObject).GetValue(indexes), returnType)); } else { int[] indexes = new int[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { indexes[i] = Convert.ToInt32(parameterValues[i]); } return(Expression.Value(((Array)targetObject).GetValue(indexes), returnType)); } } else { DefaultMemberAttribute[] att = (DefaultMemberAttribute[])targetType.GetCustomAttributes(typeof(DefaultMemberAttribute), true); MethodInfo methodInfo = targetType.GetMethod("get_" + att[0].MemberName, parameterTypes); object value = methodInfo.Invoke(targetObject, parameterValues); return(new ValueExpression(value, methodInfo.ReturnType)); } }
public override LiquidExpressionResult ApplyTo(ITemplateContext ctx, ILiquidValue liquidExpression) { return(LiquidExpressionResult.Success(StringUtils.Eval(liquidExpression, before => { return String.Concat(before.Split(new[] { ' ', '-', '_' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => char.ToUpper(x[0]) + x.Substring(1).ToLower())); }))); }
public LookupService ( ITemplateContext context, BedrockConfiguration bedrockConfiguration ) : base(bedrockConfiguration, context) { }
public IEnumerable<IExpressionConstant> Eval(ITemplateContext templateContext) { // return _stringValue.StringVal // .ToCharArray() // .Select(x => new StringValue("" + x)); // In ruby liquid, it will not iterate through a string's characters---it will treat it as an array of one string. return new List<IExpressionConstant>{_stringValue}; }
public DomainService ( ITemplateContext context, SharedConfiguration.BedrockConfiguration bedrockConfiguration ) : base(bedrockConfiguration, context) { }
public LiquidRenderingResult Render(ITemplateContext ctx) { IList <LiquidError> renderingErrors = new List <LiquidError>(); IList <LiquidError> parsingErrors = new List <LiquidError>(); return(LiquidRenderingResult.Create(Render(ctx, onRenderingError: renderingErrors.Add, onParsingError: parsingErrors.Add), renderingErrors, parsingErrors)); }
public override LiquidExpressionResult Eval(ITemplateContext templateContext, IEnumerable<Option<IExpressionConstant>> expressions) { var childExpressions = expressions.ToList(); return childExpressions.Count != 1 ? LiquidExpressionResult.Error("Unable to parse expression in parentheses") : LiquidExpressionResult.Success(childExpressions.First()); }
public override LiquidExpressionResult Eval(ITemplateContext templateContext, IEnumerable<Option<IExpressionConstant>> expressions) { var exprList = expressions.ToList(); if (exprList.Count() != 2) { throw new Exception("An AND expression must have two values"); // TODO: when the Eval is separated this will be redundant. } return LiquidExpressionResult.Success(new BooleanValue(exprList.All(x => x.HasValue) && exprList.All(x => x.Value.IsTrue))); }
public override LiquidExpressionResult Eval(ITemplateContext templateContext, IEnumerable<Option<IExpressionConstant>> expressions) { IList<Option<IExpressionConstant>> exprList = expressions.ToList(); if (exprList.Count() != 1) { return LiquidExpressionResult.Error("\"Not\" is a unary expression but received " + exprList.Count() + " arguments."); } return LiquidExpressionResult.Success(new BooleanValue(!exprList[0].HasValue || !exprList[0].Value.IsTrue)); }
public static Func<Option<IExpressionConstant>, LiquidExpressionResult> CreateChain( ITemplateContext ctx, IEnumerable<IFilterExpression> filterExpressions) { return x => { var bindAll = BindAll(ctx, InterpolateCastFilters(filterExpressions)); return bindAll(LiquidExpressionResult.Success(x)); // TODO: Is this the best way to kick off the chain? }; }
public override LiquidExpressionResult Eval(ITemplateContext templateContext, IEnumerable<Option<IExpressionConstant>> expressions) { var expressionList = expressions.ToList(); if (expressionList.Any(x => !x.HasValue)) { return LiquidExpressionResult.Success(new BooleanValue(false)); } return LiquidExpressionResult.Success(ComparisonExpressions.Compare(expressionList[0].Value, expressionList[1].Value, (x, y) => x >= y)); }
public static string RenderTemplate(string resultHello, ITemplateContext ctx = null) { if (ctx == null) { ctx = new TemplateContext(); } ctx.WithAllFilters(); var template = LiquidTemplate.Create(resultHello); return template.Render(ctx); }
private TemplateEngine(string path, ITemplateContext ctx, ICache<string, TemplateAST> cache, ExpressionLanguageEngineConfig cfg) { _ctx = ctx ?? new TemplateContext(); _cache = cache ?? NoCache.GetInstance<string, TemplateAST>(); _cfg = cfg ?? ExpressionLanguageEngineConfig.Default; if (string.IsNullOrEmpty(path)) _path = Runtime.StartupDirectory; else _path = System.IO.Path.GetFullPath(path); }
public string Include(ITemplateContext ctx, string key) { if (_lookupTable.ContainsKey(key)) { return _lookupTable[key]; } else { return ""; // TODO: check what this should return when not found. } }
public static LiquidExpressionResult Eval( TreeNode<LiquidExpression> expr, ITemplateContext templateContext) { // Evaluate the children, depth first var leaves = expr.Children.Select(x => Eval(x, templateContext)).ToList(); if (leaves.Any(x => x != null && x.IsError)) { return leaves.First(x => x.IsError); // TODO: maybe aggregate tehse } return Eval(expr.Data, leaves.Select(x => x == null ? new None<IExpressionConstant>() : x.SuccessResult), templateContext); }
public override LiquidExpressionResult Eval(ITemplateContext templateContext, IEnumerable<Option<IExpressionConstant>> expressions) { var list = expressions.ToList(); if (list.Count() != 1) { return LiquidExpressionResult.Error("Expected one variable to compare with \"present\""); } if (!list[0].HasValue) { return LiquidExpressionResult.Success(new BooleanValue(false)); // null is not present. } return LiquidExpressionResult.Success(new BooleanValue(!BlankChecker.IsBlank(list[0].Value))); }
public static LiquidExpressionResult Eval( LiquidExpressionTree expressiontree, ITemplateContext templateContext) { // Evaluate the children, depth first var leaves = expressiontree.ExpressionTree.Children.Select(x => Eval(x, templateContext)).ToList(); if (leaves.Any(x => x.IsError)) { return leaves.First(x => x.IsError); // TODO: maybe aggregate tehse } // pass the results to the parent return Eval(expressiontree.ExpressionTree.Data, leaves.Select(x => x.SuccessResult), templateContext); }
public override LiquidExpressionResult Eval(ITemplateContext templateContext, IEnumerable<Option<IExpressionConstant>> expressions) { //Console.WriteLine("** ISEMPTY EXPRESSION"); var list = expressions.ToList(); if (list.Count() != 1) { return LiquidExpressionResult.Error("Expected one variable to compare with \"empty\""); } if (!list[0].HasValue) { return LiquidExpressionResult.Success(new BooleanValue(true)); // nulls are empty. } return LiquidExpressionResult.Success(new BooleanValue(EmptyChecker.IsEmpty(list[0].Value))); }
public String Render(ITemplateContext ctx) { var result = ""; var renderingVisitor = new RenderingVisitor(ctx); renderingVisitor.StartWalking(_liquidAst.RootNode, str => result += str); if (renderingVisitor.HasErrors) { throw new LiquidRendererException(renderingVisitor.Errors); } return result; }
private void GetDiscoveryConfig(ITemplateContext templateContext, TemplateInputConfig templateConfig) { foreach (var discovery in SDKHelper.GetFolderItems<ManagementPackDiscovery>(this, templateContext.OutputFolder)) { var discoveryConfig = discovery.DataSource.Configuration; if (discovery.Name.StartsWith(ClustersDiscoveryNamePrefix, StringComparison.OrdinalIgnoreCase)) { if (WatcherNodesListNodeRegex.IsMatch(discoveryConfig)) templateConfig.WatcherNodesList = WatcherNodesListNodeRegex.Match(discoveryConfig).Groups[1].Value; } else if (discovery.Name.StartsWith(SeedDiscoveryNamePrefix, StringComparison.OrdinalIgnoreCase)) { if (SeedComputerNameNodeRegex.IsMatch(discoveryConfig)) templateConfig.SeedComputerName = SeedComputerNameNodeRegex.Match(discoveryConfig).Groups[1].Value; if (AmbariUriNodeRegex.IsMatch(discoveryConfig)) templateConfig.AmbariUri = AmbariUriNodeRegex.Match(discoveryConfig).Groups[1].Value; } } }
public static LiquidExpressionResult Eval( LiquidExpression expression, IEnumerable<Option<IExpressionConstant>> leaves, ITemplateContext templateContext) { // calculate the first part of the expression var objResult = expression.Expression == null ? LiquidExpressionResult.Success(new None<IExpressionConstant>()) : expression.Expression.Eval(templateContext, leaves); if (objResult.IsError) { return objResult; } // Compose a chain of filters, making sure type-casting // is done between them. IEnumerable<Tuple<FilterSymbol, IFilterExpression>> filterExpressionTuples; try { filterExpressionTuples = expression.FilterSymbols.Select(symbol => new Tuple<FilterSymbol, IFilterExpression>(symbol, InstantiateFilter(templateContext, symbol))) .ToList(); } catch (Exception ex) { return LiquidExpressionResult.Error(ex.Message); } var erroringFilternames = filterExpressionTuples.Where(x => x.Item2 == null).Select(x => x.Item1).ToList(); if (erroringFilternames.Any()) { //throw new Exception("Missing filters..."); //return ConstantFactory.CreateError<StringValue>(); return LiquidExpressionResult.Error("Missing filters: " + String.Join(", ", erroringFilternames.Select(x => x.Name))); } var filterChain = FilterChain.CreateChain( objResult.GetType(), templateContext, filterExpressionTuples.Select(x => x.Item2)); // apply the composed function to the object return filterChain(objResult.SuccessResult); }
public void ProcessElement(ITemplateParser parser, ITemplateContext context) { String unlessExpression = context.Reader.GetAttribute("mr:unless"); context.AppendLineIndented("if not " + unlessExpression + ":"); context.IncreaseIndentation(); // Output element parser.OutputCurrentElementAsContent(context, delegate(String attributeName) { return attributeName != "mr:unless"; }); parser.ProcessReader(context, context.CurrentElementDepth - 1); context.DecreaseIndentation(); }
public string Process(string template, ITemplateContext context) { using(var writer = new StringWriter()) { try { Evaluate(CreateNVelocityContext(context.Items), writer, "nu", template); } catch (ParseErrorException pe) { return pe.Message; } catch (MethodInvocationException mi) { return mi.Message; } return writer.ToString(); } }
public IEnumerable<IExpressionConstant> Eval(ITemplateContext templateContext) { var expressionConstant = LiquidExpressionEvaluator.Eval(_arrayValueExpression, templateContext); if (expressionConstant.IsError || !expressionConstant.SuccessResult.HasValue) { return new List<IExpressionConstant>(); } var castResult = ValueCaster.Cast<IExpressionConstant, ArrayValue>(expressionConstant.SuccessResult.Value); if (castResult.IsError) { // ?? return new List<IExpressionConstant>(); } else { return castResult.SuccessValue<ArrayValue>().Select(x => x.HasValue? x.Value : null); } }
public static Func<LiquidExpressionResult, LiquidExpressionResult> BindAll( ITemplateContext ctx, IEnumerable<IFilterExpression> filterExpressions) { return initValue => filterExpressions.Aggregate(initValue, (current, filter) => { if (initValue.IsError) { return initValue; } if (current.IsError) { return current; } return current.SuccessResult.HasValue ? filter.Apply(ctx, current.SuccessResult.Value) : filter.ApplyToNil(ctx); }); }
/// <summary> /// Create a chain of functions that returns a value of type resultType. If function #1 doesn't /// return a T, a casting function will be interpolated into the chain. /// </summary> /// <returns></returns> public static Func<Option<IExpressionConstant>, LiquidExpressionResult> CreateChain( Type objExprType, ITemplateContext ctx, IEnumerable<IFilterExpression> filterExpressions) { var expressions = filterExpressions.ToList(); if (!expressions.Any()) { return x => new LiquidExpressionResult(x); } // create the casting filter which will cast the incoming object to the input type of filter #1 Func<IExpressionConstant, LiquidExpressionResult> castFn = objExpr => objExpr!=null ? CreateCastFilter(objExpr.GetType(), expressions[0].SourceType).Apply(ctx, objExpr) : LiquidExpressionResult.Success(new None<IExpressionConstant>()); return optionExpression => (castFn(optionExpression.HasValue ? optionExpression.Value : null)).Bind(CreateChain(ctx, expressions)); }
public string Include(ITemplateContext ctx, string key) { String result = key; switch (key) { case "product": result = "Product: {{ product.title }} "; break; case "locale_variables": result = "Locale: {{echo1}} {{echo2}}"; break; case "variant": result = "Variant: {{ variant.title }}"; break; case "nested_template": result = "{% include 'header' %} {% include 'body' %} {% include 'footer' %}"; break; case "body": result = "body {% include 'body_detail' %}"; break; case "nested_product_template": result = "Product: {{ nested_product_template.title }} {%include 'details'%} "; break; case "recursively_nested_template": result = "-{% include 'recursively_nested_template' %}"; break; case "pick_a_source": result = "from TestFileSystem"; break; case "assignments": result = "{% assign foo = 'bar' %}"; break; } return result; }
private LiquidExpressionResult DoLookup(ITemplateContext ctx, ArrayValue arrayValue, IExpressionConstant indexProperty) { String propertyNameString = ValueCaster.RenderAsString(indexProperty); int index; if (propertyNameString.ToLower().Equals("first")) { index = 0; } else if (propertyNameString.ToLower().Equals("last")) { index = arrayValue.ArrValue.Count - 1; } else if (propertyNameString.ToLower().Equals("size")) { return LiquidExpressionResult.Success(NumericValue.Create(arrayValue.ArrValue.Count)); } else { var maybeIndexResult = ValueCaster.Cast<IExpressionConstant, NumericValue>(indexProperty); if (maybeIndexResult.IsError || !maybeIndexResult.SuccessResult.HasValue) { return LiquidExpressionResult.Error("invalid array index: " + propertyNameString); } else { index = maybeIndexResult.SuccessValue<NumericValue>().IntValue; } } if (arrayValue.ArrValue.Count == 0) { //return LiquidExpressionResult.Error("array is empty: " + propertyNameString); return LiquidExpressionResult.Success(new None<IExpressionConstant>()); // not an error in Ruby liquid. } var result = arrayValue.ValueAt(index); return LiquidExpressionResult.Success(result); }
public StringValue Render( RenderingVisitor renderingVisitor, MacroBlockTag macroBlocktag, ITemplateContext templateContext, IList<Option<IExpressionConstant>> args) { var macroScope = new SymbolTable(); var i = 0; foreach (var varName in macroBlocktag.Args.Take(args.Count)) { macroScope.DefineLocalVariable(varName, args[i].HasValue? args[i].Value : null); i++; } templateContext.SymbolTableStack.Push(macroScope); //String result = ""; //var subRenderer = new RenderingVisitor(evaluator, templateContext, str => result += str); //evaluator.StartVisiting(subRenderer, macroBlocktag.LiquidBlock); String hiddenText = ""; renderingVisitor.PushTextAccumulator(str => hiddenText += str); renderingVisitor.StartWalking(macroBlocktag.LiquidBlock); renderingVisitor.PopTextAccumulator(); templateContext.SymbolTableStack.Pop(); // foreach (var error in subRenderer.Errors) // { // errorAccumulator.Add(error); // } return new StringValue(hiddenText); }
public void ProcessElement(ITemplateParser parser, ITemplateContext context) { String view = context.Reader.GetAttribute("src") + IronPythonViewEngine.TemplateExtension; IViewSourceLoader loader = (IViewSourceLoader) context.ServiceProvider.GetService(typeof(IViewSourceLoader)); IViewSource source = loader.GetViewSource(view); if (source == null) { throw new RailsException("RenderPartial: could not find view [" + view + "]"); } String functionName; context.Engine.CompilePartialTemplate(source, view, out functionName); context.Script.AppendLine(); context.AppendIndented(functionName); context.Script.Append('('); context.Script.Append("controller, context, request, response, session, output, flash, siteroot"); context.Script.Append(')'); context.Script.AppendLine(); }