Search in sources :

Example 1 with TemplateModel

use of org.thymeleaf.engine.TemplateModel in project thymeleaf by thymeleaf.

the class AbstractStandardInliner method inlineSwitchTemplateMode.

private CharSequence inlineSwitchTemplateMode(final ITemplateContext context, final IComment comment) {
    final TemplateManager templateManager = context.getConfiguration().getTemplateManager();
    /*
         * Notice we are ONLY processing the contents of the Comment, because we know the target inlining
         * mode will not understand the Comment (it will be textual) and we don't want it to mess around with
         * the Comment's prefix and suffix.
         *
         * Note this will only be executed in markup modes (textual modes never fire "handleComment" events),
         * so we are safe assuming the sizes of Comment prefixes and suffixes in HTML/XML.
         */
    final TemplateModel templateModel = templateManager.parseString(context.getTemplateData(), comment.getContent(), // +4 because of the prefix
    comment.getLine(), // +4 because of the prefix
    comment.getCol() + 4, this.templateMode, true);
    final Writer stringWriter = new FastStringWriter(50);
    templateManager.process(templateModel, context, stringWriter);
    return stringWriter.toString();
}
Also used : FastStringWriter(org.thymeleaf.util.FastStringWriter) TemplateManager(org.thymeleaf.engine.TemplateManager) TemplateModel(org.thymeleaf.engine.TemplateModel) FastStringWriter(org.thymeleaf.util.FastStringWriter) Writer(java.io.Writer)

Example 2 with TemplateModel

use of org.thymeleaf.engine.TemplateModel in project thymeleaf by thymeleaf.

the class AbstractStandardInliner method inlineSwitchTemplateMode.

private CharSequence inlineSwitchTemplateMode(final ITemplateContext context, final IText text) {
    final TemplateManager templateManager = context.getConfiguration().getTemplateManager();
    final TemplateModel templateModel = templateManager.parseString(context.getTemplateData(), text.getText(), text.getLine(), text.getCol(), this.templateMode, true);
    if (!this.writeTextsToOutput) {
        final Writer stringWriter = new FastStringWriter(50);
        templateManager.process(templateModel, context, stringWriter);
        return stringWriter.toString();
    }
    // If we can directly write to output (and text is an IText), we will use a LazyProcessingCharSequence
    return new LazyProcessingCharSequence(context, templateModel);
}
Also used : LazyProcessingCharSequence(org.thymeleaf.util.LazyProcessingCharSequence) FastStringWriter(org.thymeleaf.util.FastStringWriter) TemplateManager(org.thymeleaf.engine.TemplateManager) TemplateModel(org.thymeleaf.engine.TemplateModel) FastStringWriter(org.thymeleaf.util.FastStringWriter) Writer(java.io.Writer)

Example 3 with TemplateModel

use of org.thymeleaf.engine.TemplateModel in project thymeleaf by thymeleaf.

the class FragmentExpression method resolveExecutedFragmentExpression.

public static Fragment resolveExecutedFragmentExpression(final ITemplateContext context, final ExecutedFragmentExpression executedFragmentExpression, final boolean failIfNotExists) {
    if (executedFragmentExpression == ExecutedFragmentExpression.EMPTY_EXECUTED_FRAGMENT_EXPRESSION) {
        return Fragment.EMPTY_FRAGMENT;
    }
    final IEngineConfiguration configuration = context.getConfiguration();
    /*
         * COMPUTE template name as String
         */
    String templateName = resolveTemplateName(executedFragmentExpression);
    /*
         * COMPUTE fragment selector as String
         */
    final Set<String> fragments = resolveFragments(executedFragmentExpression);
    /*
         * RESOLVE THE FRAGMENT MODEL by using the TemplateManager. This means the fragment will be parsed and maybe
         * cached, and we will be returned an immutable model object
         */
    List<String> templateNameStack = null;
    // scan the template stack if template name is 'this' or an empty name is being used
    if (StringUtils.isEmptyOrWhitespace(templateName)) {
        if (fragments == null || fragments.isEmpty()) {
            return null;
        }
        templateNameStack = new ArrayList<String>(3);
        for (int i = context.getTemplateStack().size() - 1; i >= 0; i--) {
            templateNameStack.add(context.getTemplateStack().get(i).getTemplate());
        }
        templateName = templateNameStack.get(0);
    }
    TemplateModel fragmentModel;
    int i = 0;
    do {
        fragmentModel = configuration.getTemplateManager().parseStandalone(context, templateName, fragments, // we will not force the template mode
        null, // use the cache if possible, fragments are from template files
        true, // depending on the scenario we will consider a non exiting template a fail or not
        failIfNotExists);
        i++;
    } while (// template not found (only if resolver configuration allows)
    fragmentModel != null && // template found, but selector not found
    fragmentModel.size() <= 2 && // we have more templates to look into
    templateNameStack != null && // we have more templates to look into
    i < templateNameStack.size() && // post test -- need to parse at least 1x
    (templateName = templateNameStack.get(i)) != null);
    if (fragmentModel == null) {
        // such as "~{template} ? ~{default}"
        return null;
    }
    /*
         * We should now check if the resolved fragment actually exists or not (we know the template exists but,
         * did the fragment actually return anything at all?
         */
    // only templatestart/end
    final boolean fragmentIsEmpty = (fragmentModel.size() == 2);
    if (fragmentIsEmpty) {
        // either fail or simply return null
        if (failIfNotExists) {
            throw new TemplateInputException("Error resolving fragment: \"" + executedFragmentExpression.fragmentExpression.getStringRepresentation() + "\": " + "template or fragment could not be resolved");
        }
        return null;
    }
    /*
         * RETURN the expected Fragment object
         */
    return new Fragment(fragmentModel, executedFragmentExpression.fragmentParameters, executedFragmentExpression.syntheticParameters);
}
Also used : IEngineConfiguration(org.thymeleaf.IEngineConfiguration) TemplateModel(org.thymeleaf.engine.TemplateModel) TemplateInputException(org.thymeleaf.exceptions.TemplateInputException)

Example 4 with TemplateModel

use of org.thymeleaf.engine.TemplateModel in project thymeleaf by thymeleaf.

the class AbstractStandardInliner method inlineSwitchTemplateMode.

private CharSequence inlineSwitchTemplateMode(final ITemplateContext context, final ICDATASection cdataSection) {
    final TemplateManager templateManager = context.getConfiguration().getTemplateManager();
    /*
         * Notice we are ONLY processing the contents of the CDATA, because we know the target inlining
         * mode will not understand the CDATA (it will be textual) and we don't want it to mess around with
         * the CDATA's prefix and suffix.
         *
         * Note this will only be executed in markup modes (textual modes never fire "handleCDATASection" events),
         * so we are safe assuming the sizes of CDATA prefixes and suffixes in HTML/XML.
         */
    final TemplateModel templateModel = templateManager.parseString(context.getTemplateData(), cdataSection.getContent(), // +9 because of the prefix
    cdataSection.getLine(), // +9 because of the prefix
    cdataSection.getCol() + 9, this.templateMode, true);
    final Writer stringWriter = new FastStringWriter(50);
    templateManager.process(templateModel, context, stringWriter);
    return stringWriter.toString();
}
Also used : FastStringWriter(org.thymeleaf.util.FastStringWriter) TemplateManager(org.thymeleaf.engine.TemplateManager) TemplateModel(org.thymeleaf.engine.TemplateModel) FastStringWriter(org.thymeleaf.util.FastStringWriter) Writer(java.io.Writer)

Example 5 with TemplateModel

use of org.thymeleaf.engine.TemplateModel in project thymeleaf by thymeleaf.

the class AbstractStandardFragmentInsertionTagProcessor method doProcess.

@Override
protected void doProcess(final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {
    if (StringUtils.isEmptyOrWhitespace(attributeValue)) {
        throw new TemplateProcessingException("Fragment specifications cannot be empty");
    }
    final IEngineConfiguration configuration = context.getConfiguration();
    /*
         * PARSE AND PROCESS THE FRAGMENT
         */
    final Object fragmentObj = computeFragment(context, attributeValue);
    if (fragmentObj == null) {
        throw new TemplateInputException("Error resolving fragment: \"" + attributeValue + "\": " + "template or fragment could not be resolved");
    } else if (fragmentObj == NoOpToken.VALUE) {
        // If the Fragment result is NO-OP, we will just do nothing (apart from deleting the th:* attribute)
        return;
    } else if (fragmentObj == Fragment.EMPTY_FRAGMENT) {
        // tag (th:insert) or remove it completely, tag included (th:replace)
        if (this.replaceHost) {
            structureHandler.removeElement();
        } else {
            structureHandler.removeBody();
        }
        return;
    }
    final Fragment fragment = (Fragment) fragmentObj;
    final TemplateModel fragmentModel = fragment.getTemplateModel();
    Map<String, Object> fragmentParameters = fragment.getParameters();
    /*
         * ONCE WE HAVE THE FRAGMENT MODEL (its events, in fact), CHECK THE FRAGMENT SIGNATURE
         * Fragment signature is important because it might affect the way we apply the parameters to the fragment.
         *
         * Note this works whatever the template mode of the inserted fragment, given we are looking for an
         * element containing a "th:fragment/data-th-fragment" in a generic, non-template-dependent way.
         */
    // We will check types first instead of events in order to (many times) avoid creating an immutably-wrapped
    // event object when calling "model.get(pos)"
    boolean signatureApplied = false;
    final ITemplateEvent firstEvent = (fragmentModel.size() > 2 ? fragmentModel.get(1) : null);
    if (firstEvent != null && IProcessableElementTag.class.isAssignableFrom(firstEvent.getClass())) {
        final String dialectPrefix = attributeName.getPrefix();
        final IProcessableElementTag fragmentHolderEvent = (IProcessableElementTag) firstEvent;
        if (fragmentHolderEvent.hasAttribute(dialectPrefix, FRAGMENT_ATTR_NAME)) {
            // The selected fragment actually has a "th:fragment" attribute, so we should process its signature
            final String fragmentSignatureSpec = EscapedAttributeUtils.unescapeAttribute(fragmentModel.getTemplateMode(), fragmentHolderEvent.getAttributeValue(dialectPrefix, FRAGMENT_ATTR_NAME));
            if (!StringUtils.isEmptyOrWhitespace(fragmentSignatureSpec)) {
                final FragmentSignature fragmentSignature = FragmentSignatureUtils.parseFragmentSignature(configuration, fragmentSignatureSpec);
                if (fragmentSignature != null) {
                    // Reshape the fragment parameters into the ones that we will actually use, according to the signature
                    fragmentParameters = FragmentSignatureUtils.processParameters(fragmentSignature, fragmentParameters, fragment.hasSyntheticParameters());
                    signatureApplied = true;
                }
            }
        }
    }
    // not being applied, maybe not realising there was no signature assignation involved.
    if (!signatureApplied && fragment.hasSyntheticParameters()) {
        throw new TemplateProcessingException("Fragment '" + attributeValue + "' specifies synthetic (unnamed) parameters, but the resolved fragment " + "does not match a fragment signature (th:fragment,data-th-fragment) which could apply names to " + "the specified parameters.");
    }
    /*
         * CHECK WHETHER THIS IS A CROSS-TEMPLATE-MODE INSERTION. Only TemplateModels for the same template mode
         * can be safely inserted into the template being executed and processed just like any other sequences of
         * events. If the inserted template has a different template mode, we will need to process it aside and
         * obtain a String result for it, then insert such String as mere text.
         *
         * Note inserting large templates with a different template mode could therefore have a negative effect
         * on performance and memory usage, as their result needs to be completely stored in memory at some point
         * before being handled to the following phases of template processing. It is therefore recommended that
         * cross-template-mode fragment insertion is done only for small fragments, in which case it will work
         * almost the same as inlining (with the exception that the content to be inlined will be retrieved from
         * somewhere else by means of template resolution).
         */
    if (context.getTemplateMode() != fragmentModel.getTemplateMode()) {
        // Check if this is a th:include. If so, just don't allow
        if (this.insertOnlyContents) {
            throw new TemplateProcessingException("Template being processed uses template mode " + context.getTemplateMode() + ", " + "inserted fragment \"" + attributeValue + "\" uses template mode " + fragmentModel.getTemplateMode() + ". Cross-template-mode fragment insertion is not " + "allowed using the " + attributeName + " attribute, which is no longer recommended for use as " + "of Thymeleaf 3.0. Use {th:insert,data-th-insert} or {th:replace,data-th-replace} " + "instead, which do not remove the container element from the fragment being inserted.");
        }
        // doing it through the structure handler (we are going to perform a nested template processing operation)
        if (fragmentParameters != null && fragmentParameters.size() > 0) {
            if (!(context instanceof IEngineContext)) {
                throw new TemplateProcessingException("Parameterized fragment insertion is not supported because local variable support is DISABLED. This is due to " + "the use of an implementation of the " + ITemplateContext.class.getName() + " interface that does " + "not provide local-variable support. In order to have local-variable support, the variables map " + "implementation should also implement the " + IEngineContext.class.getName() + " interface");
            }
            // NOTE this IEngineContext interface is internal and should not be used in users' code
            ((IEngineContext) context).setVariables(fragmentParameters);
        }
        // Once parameters are in order, just process the template in a nested template engine execution
        final Writer stringWriter = new FastStringWriter(200);
        configuration.getTemplateManager().process(fragmentModel, context, stringWriter);
        // We will insert the result as NON-PROCESSABLE text (it's already been processed!)
        if (this.replaceHost) {
            structureHandler.replaceWith(stringWriter.toString(), false);
        } else {
            structureHandler.setBody(stringWriter.toString(), false);
        }
        return;
    }
    /*
         * APPLY THE FRAGMENT'S TEMPLATE RESOLUTION so that all code inside the fragment is executed with its own
         * template resolution info (working as if it were a local variable)
         */
    final TemplateData fragmentTemplateData = fragmentModel.getTemplateData();
    structureHandler.setTemplateData(fragmentTemplateData);
    /*
         * APPLY THE FRAGMENT PARAMETERS AS LOCAL VARIABLES, perhaps after reshaping it according to the fragment signature
         */
    if (fragmentParameters != null && fragmentParameters.size() > 0) {
        for (final Map.Entry<String, Object> fragmentParameterEntry : fragmentParameters.entrySet()) {
            structureHandler.setLocalVariable(fragmentParameterEntry.getKey(), fragmentParameterEntry.getValue());
        }
    }
    /*
         * IF WE ARE ASKING ONLY FOR CONTENTS (th:include), THEN REMOVE THE CONTAINER BLOCK
         */
    if (this.insertOnlyContents && fragmentTemplateData.hasTemplateSelectors()) {
        /*
             * In the case of th:include, things get a bit complicated because we need to remove the "element envelopes"
             * that contain what we really want to include (these envelopes' contents). So we will need to traverse
             * the entire returned model detecting those envelopes (open+close tags at model level == 0) and remove
             * them, along with anything else that is also at that level 0.
             */
        final IModel model = fragmentModel.cloneModel();
        int modelLevel = 0;
        int n = model.size();
        while (n-- != 0) {
            // We traverse backwards so that we can modify at the same time
            final ITemplateEvent event = model.get(n);
            if (event instanceof ICloseElementTag) {
                if (((ICloseElementTag) event).isUnmatched()) {
                    // This is an unmatched close tag (no corresponding open), therefore should not affect our count
                    continue;
                }
                if (modelLevel <= 0) {
                    model.remove(n);
                }
                modelLevel++;
                continue;
            }
            if (event instanceof IOpenElementTag) {
                modelLevel--;
                if (modelLevel <= 0) {
                    model.remove(n);
                }
                continue;
            }
            if (modelLevel <= 0) {
                model.remove(n);
            }
        }
        if (this.replaceHost) {
            structureHandler.replaceWith(model, true);
        } else {
            structureHandler.setBody(model, true);
        }
        return;
    }
    if (this.replaceHost) {
        structureHandler.replaceWith(fragmentModel, true);
    } else {
        structureHandler.setBody(fragmentModel, true);
    }
}
Also used : ITemplateEvent(org.thymeleaf.model.ITemplateEvent) IModel(org.thymeleaf.model.IModel) IEngineConfiguration(org.thymeleaf.IEngineConfiguration) IOpenElementTag(org.thymeleaf.model.IOpenElementTag) FragmentSignature(org.thymeleaf.standard.expression.FragmentSignature) TemplateModel(org.thymeleaf.engine.TemplateModel) Fragment(org.thymeleaf.standard.expression.Fragment) TemplateInputException(org.thymeleaf.exceptions.TemplateInputException) IEngineContext(org.thymeleaf.context.IEngineContext) TemplateData(org.thymeleaf.engine.TemplateData) IProcessableElementTag(org.thymeleaf.model.IProcessableElementTag) FastStringWriter(org.thymeleaf.util.FastStringWriter) TemplateProcessingException(org.thymeleaf.exceptions.TemplateProcessingException) ITemplateContext(org.thymeleaf.context.ITemplateContext) Map(java.util.Map) FastStringWriter(org.thymeleaf.util.FastStringWriter) Writer(java.io.Writer) ICloseElementTag(org.thymeleaf.model.ICloseElementTag)

Aggregations

TemplateModel (org.thymeleaf.engine.TemplateModel)7 FastStringWriter (org.thymeleaf.util.FastStringWriter)5 Writer (java.io.Writer)4 TemplateManager (org.thymeleaf.engine.TemplateManager)4 IEngineConfiguration (org.thymeleaf.IEngineConfiguration)3 TemplateInputException (org.thymeleaf.exceptions.TemplateInputException)2 Fragment (org.thymeleaf.standard.expression.Fragment)2 Map (java.util.Map)1 IEngineContext (org.thymeleaf.context.IEngineContext)1 ITemplateContext (org.thymeleaf.context.ITemplateContext)1 TemplateData (org.thymeleaf.engine.TemplateData)1 TemplateProcessingException (org.thymeleaf.exceptions.TemplateProcessingException)1 ICloseElementTag (org.thymeleaf.model.ICloseElementTag)1 IModel (org.thymeleaf.model.IModel)1 IOpenElementTag (org.thymeleaf.model.IOpenElementTag)1 IProcessableElementTag (org.thymeleaf.model.IProcessableElementTag)1 ITemplateEvent (org.thymeleaf.model.ITemplateEvent)1 IPostProcessor (org.thymeleaf.postprocessor.IPostProcessor)1 FragmentExpression (org.thymeleaf.standard.expression.FragmentExpression)1 FragmentSignature (org.thymeleaf.standard.expression.FragmentSignature)1