Search in sources :

Example 1 with TemplateScalarModel

use of freemarker.template.TemplateScalarModel in project freemarker by apache.

the class DynamicKeyName method _eval.

@Override
TemplateModel _eval(Environment env) throws TemplateException {
    TemplateModel targetModel = target.eval(env);
    if (targetModel == null) {
        if (env.isClassicCompatible()) {
            return null;
        } else {
            throw InvalidReferenceException.getInstance(target, env);
        }
    }
    TemplateModel keyModel = keyExpression.eval(env);
    if (keyModel == null) {
        if (env.isClassicCompatible()) {
            keyModel = TemplateScalarModel.EMPTY_STRING;
        } else {
            keyExpression.assertNonNull(null, env);
        }
    }
    if (keyModel instanceof TemplateNumberModel) {
        int index = keyExpression.modelToNumber(keyModel, env).intValue();
        return dealWithNumericalKey(targetModel, index, env);
    }
    if (keyModel instanceof TemplateScalarModel) {
        String key = EvalUtil.modelToString((TemplateScalarModel) keyModel, keyExpression, env);
        return dealWithStringKey(targetModel, key, env);
    }
    if (keyModel instanceof RangeModel) {
        return dealWithRangeKey(targetModel, (RangeModel) keyModel, env);
    }
    throw new UnexpectedTypeException(keyExpression, keyModel, "number, range, or string", new Class[] { TemplateNumberModel.class, TemplateScalarModel.class, Range.class }, env);
}
Also used : TemplateNumberModel(freemarker.template.TemplateNumberModel) TemplateScalarModel(freemarker.template.TemplateScalarModel) TemplateModel(freemarker.template.TemplateModel)

Example 2 with TemplateScalarModel

use of freemarker.template.TemplateScalarModel in project freemarker by apache.

the class GetOptionalTemplateMethod method exec.

public Object exec(List args) throws TemplateModelException {
    final int argCnt = args.size();
    if (argCnt < 1 || argCnt > 2) {
        throw _MessageUtil.newArgCntError(methodName, argCnt, 1, 2);
    }
    final Environment env = Environment.getCurrentEnvironment();
    if (env == null) {
        throw new IllegalStateException("No freemarer.core.Environment is associated to the current thread.");
    }
    final String absTemplateName;
    {
        TemplateModel arg = (TemplateModel) args.get(0);
        if (!(arg instanceof TemplateScalarModel)) {
            throw _MessageUtil.newMethodArgMustBeStringException(methodName, 0, arg);
        }
        String templateName = EvalUtil.modelToString((TemplateScalarModel) arg, null, env);
        try {
            absTemplateName = env.toFullTemplateName(env.getCurrentTemplate().getName(), templateName);
        } catch (MalformedTemplateNameException e) {
            throw new _TemplateModelException(e, "Failed to convert template path to full path; see cause exception.");
        }
    }
    final TemplateHashModelEx options;
    if (argCnt > 1) {
        TemplateModel arg = (TemplateModel) args.get(1);
        if (!(arg instanceof TemplateHashModelEx)) {
            throw _MessageUtil.newMethodArgMustBeExtendedHashException(methodName, 1, arg);
        }
        options = (TemplateHashModelEx) arg;
    } else {
        options = null;
    }
    String encoding = null;
    boolean parse = true;
    if (options != null) {
        final KeyValuePairIterator kvpi = TemplateModelUtils.getKeyValuePairIterator(options);
        while (kvpi.hasNext()) {
            final KeyValuePair kvp = kvpi.next();
            final String optName;
            {
                TemplateModel optNameTM = kvp.getKey();
                if (!(optNameTM instanceof TemplateScalarModel)) {
                    throw _MessageUtil.newMethodArgInvalidValueException(methodName, 1, "All keys in the options hash must be strings, but found ", new _DelayedAOrAn(new _DelayedFTLTypeDescription(optNameTM)));
                }
                optName = ((TemplateScalarModel) optNameTM).getAsString();
            }
            final TemplateModel optValue = kvp.getValue();
            if (OPTION_ENCODING.equals(optName)) {
                encoding = getStringOption(OPTION_ENCODING, optValue);
            } else if (OPTION_PARSE.equals(optName)) {
                parse = getBooleanOption(OPTION_PARSE, optValue);
            } else {
                throw _MessageUtil.newMethodArgInvalidValueException(methodName, 1, "Unsupported option ", new _DelayedJQuote(optName), "; valid names are: ", new _DelayedJQuote(OPTION_ENCODING), ", ", new _DelayedJQuote(OPTION_PARSE), ".");
            }
        }
    }
    final Template template;
    try {
        template = env.getTemplateForInclusion(absTemplateName, encoding, parse, true);
    } catch (IOException e) {
        throw new _TemplateModelException(e, "I/O error when trying to load optional template ", new _DelayedJQuote(absTemplateName), "; see cause exception");
    }
    SimpleHash result = new SimpleHash(env.getObjectWrapper());
    result.put(RESULT_EXISTS, template != null);
    // conveniently provided like in <@optTemp.include!myDefaultMacro />.
    if (template != null) {
        result.put(RESULT_INCLUDE, new TemplateDirectiveModel() {

            public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
                if (!params.isEmpty()) {
                    throw new TemplateException("This directive supports no parameters.", env);
                }
                if (loopVars.length != 0) {
                    throw new TemplateException("This directive supports no loop variables.", env);
                }
                if (body != null) {
                    throw new TemplateException("This directive supports no nested content.", env);
                }
                env.include(template);
            }
        });
        result.put(RESULT_IMPORT, new TemplateMethodModelEx() {

            public Object exec(List args) throws TemplateModelException {
                if (!args.isEmpty()) {
                    throw new TemplateModelException("This method supports no parameters.");
                }
                try {
                    return env.importLib(template, null);
                } catch (IOException e) {
                    throw new _TemplateModelException(e, "Failed to import loaded template; see cause exception");
                } catch (TemplateException e) {
                    throw new _TemplateModelException(e, "Failed to import loaded template; see cause exception");
                }
            }
        });
    }
    return result;
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) TemplateModel(freemarker.template.TemplateModel) MalformedTemplateNameException(freemarker.template.MalformedTemplateNameException) Template(freemarker.template.Template) TemplateMethodModelEx(freemarker.template.TemplateMethodModelEx) List(java.util.List) KeyValuePairIterator(freemarker.template.TemplateHashModelEx2.KeyValuePairIterator) KeyValuePair(freemarker.template.TemplateHashModelEx2.KeyValuePair) TemplateException(freemarker.template.TemplateException) IOException(java.io.IOException) TemplateDirectiveBody(freemarker.template.TemplateDirectiveBody) TemplateHashModelEx(freemarker.template.TemplateHashModelEx) SimpleHash(freemarker.template.SimpleHash) TemplateScalarModel(freemarker.template.TemplateScalarModel) Map(java.util.Map) TemplateDirectiveModel(freemarker.template.TemplateDirectiveModel)

Example 3 with TemplateScalarModel

use of freemarker.template.TemplateScalarModel in project freemarker by apache.

the class Include method accept.

@Override
TemplateElement[] accept(Environment env) throws TemplateException, IOException {
    final String includedTemplateName = includedTemplateNameExp.evalAndCoerceToPlainText(env);
    final String fullIncludedTemplateName;
    try {
        fullIncludedTemplateName = env.toFullTemplateName(getTemplate().getName(), includedTemplateName);
    } catch (MalformedTemplateNameException e) {
        throw new _MiscTemplateException(e, env, "Malformed template name ", new _DelayedJQuote(e.getTemplateName()), ":\n", e.getMalformednessDescription());
    }
    final String encoding = this.encoding != null ? this.encoding : (encodingExp != null ? encodingExp.evalAndCoerceToPlainText(env) : null);
    final boolean parse;
    if (this.parse != null) {
        parse = this.parse.booleanValue();
    } else {
        TemplateModel tm = parseExp.eval(env);
        if (tm instanceof TemplateScalarModel) {
            // Legacy
            parse = getYesNo(parseExp, EvalUtil.modelToString((TemplateScalarModel) tm, parseExp, env));
        } else {
            parse = parseExp.modelToBoolean(tm, env);
        }
    }
    final boolean ignoreMissing;
    if (this.ignoreMissingExpPrecalcedValue != null) {
        ignoreMissing = this.ignoreMissingExpPrecalcedValue.booleanValue();
    } else if (ignoreMissingExp != null) {
        ignoreMissing = ignoreMissingExp.evalToBoolean(env);
    } else {
        ignoreMissing = false;
    }
    final Template includedTemplate;
    try {
        includedTemplate = env.getTemplateForInclusion(fullIncludedTemplateName, encoding, parse, ignoreMissing);
    } catch (IOException e) {
        throw new _MiscTemplateException(e, env, "Template inclusion failed (for parameter value ", new _DelayedJQuote(includedTemplateName), "):\n", new _DelayedGetMessage(e));
    }
    if (includedTemplate != null) {
        env.include(includedTemplate);
    }
    return null;
}
Also used : TemplateScalarModel(freemarker.template.TemplateScalarModel) TemplateModel(freemarker.template.TemplateModel) IOException(java.io.IOException) MalformedTemplateNameException(freemarker.template.MalformedTemplateNameException) Template(freemarker.template.Template)

Example 4 with TemplateScalarModel

use of freemarker.template.TemplateScalarModel in project be5 by DevelopmentOnTheEdge.

the class FtlToYaml method ftlToHash.

public static LinkedHashMap<String, Object> ftlToHash(TemplateHashModelEx model) throws TemplateModelException {
    LinkedHashMap<String, Object> result = new LinkedHashMap<>();
    TemplateCollectionModel keys = model.keys();
    TemplateModelIterator iterator = keys.iterator();
    while (iterator.hasNext()) {
        TemplateModel next = iterator.next();
        if (!(next instanceof TemplateScalarModel)) {
            throw new TemplateModelException("Invalid key: " + next);
        }
        String key = ((TemplateScalarModel) next).getAsString();
        TemplateModel value = model.get(key);
        try {
            result.put(key, ftlToObject(value));
        } catch (TemplateModelException e) {
            throw new TemplateModelException(key + ": " + e.getMessage(), e);
        }
    }
    return result;
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) TemplateModelIterator(freemarker.template.TemplateModelIterator) TemplateScalarModel(freemarker.template.TemplateScalarModel) TemplateModel(freemarker.template.TemplateModel) TemplateCollectionModel(freemarker.template.TemplateCollectionModel) LinkedHashMap(java.util.LinkedHashMap)

Example 5 with TemplateScalarModel

use of freemarker.template.TemplateScalarModel in project be5 by DevelopmentOnTheEdge.

the class Project method getVariableValue.

/**
 * Returns the value of FreeMarker variable defined in the project
 * @param name
 * @return variable value converted to string
 * @throws ProjectElementException
 */
public String getVariableValue(String name) {
    if (name == null || name.isEmpty())
        return null;
    try {
        Template template = new Template("", "", getConfiguration());
        Environment environment = template.createProcessingEnvironment(getContext(null), new StringWriter());
        environment.process();
        Object value = environment.__getitem__(name);
        if (value instanceof TemplateScalarModel) {
            return ((TemplateScalarModel) value).getAsString();
        }
        if (value == null) {
            return null;
        }
        return value.toString();
    } catch (IOException | TemplateException e) {
        throw new RuntimeException("Unexpected exception in getVariableValue: " + e);
    }
}
Also used : StringWriter(java.io.StringWriter) TemplateException(freemarker.template.TemplateException) Environment(freemarker.core.Environment) TemplateScalarModel(freemarker.template.TemplateScalarModel) IOException(java.io.IOException) Template(freemarker.template.Template)

Aggregations

TemplateScalarModel (freemarker.template.TemplateScalarModel)41 TemplateModel (freemarker.template.TemplateModel)18 TemplateModelException (freemarker.template.TemplateModelException)18 TemplateHashModel (freemarker.template.TemplateHashModel)9 TemplateSequenceModel (freemarker.template.TemplateSequenceModel)9 IOException (java.io.IOException)9 TemplateNumberModel (freemarker.template.TemplateNumberModel)8 Environment (freemarker.core.Environment)7 BeanModel (freemarker.ext.beans.BeanModel)7 TemplateMethodModelEx (freemarker.template.TemplateMethodModelEx)7 SimpleScalar (freemarker.template.SimpleScalar)6 Test (org.junit.Test)6 SimpleSequence (freemarker.template.SimpleSequence)5 Template (freemarker.template.Template)5 TemplateNodeModel (freemarker.template.TemplateNodeModel)5 Writer (java.io.Writer)5 Map (java.util.Map)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 TemplateBooleanModel (freemarker.template.TemplateBooleanModel)4 TemplateException (freemarker.template.TemplateException)3