Search in sources :

Example 1 with ITemplateResource

use of org.thymeleaf.templateresource.ITemplateResource in project thymeleaf-tests by thymeleaf.

the class SpringResourceTemplateResolverSpring4Test method testResolveTemplate.

@Test
public void testResolveTemplate() throws Exception {
    final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    final IEngineConfiguration configuration = templateEngine.getConfiguration();
    final String templateLocation = "spring5/templateresolver/test.html";
    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring5/templateresolver/applicationContext.xml");
    final SpringResourceTemplateResolver resolver = (SpringResourceTemplateResolver) context.getBean("springResourceTemplateResolver");
    final TemplateMode templateMode = resolver.getTemplateMode();
    Assert.assertEquals(TemplateMode.HTML, templateMode);
    final TemplateResolution resolution = resolver.resolveTemplate(configuration, null, "classpath:" + templateLocation, null);
    final ITemplateResource templateResource = resolution.getTemplateResource();
    final String templateResourceStr = IOUtils.toString(templateResource.reader());
    final String testResource = templateResourceStr.replace("\r", "");
    final String expected = ResourceUtils.read(ClassLoaderUtils.getClassLoader(SpringResourceTemplateResolverSpring4Test.class).getResourceAsStream(templateLocation), "US-ASCII", true).replace("\r", "");
    Assert.assertEquals(expected, testResource);
}
Also used : SpringTemplateEngine(org.thymeleaf.spring5.SpringTemplateEngine) TemplateMode(org.thymeleaf.templatemode.TemplateMode) IEngineConfiguration(org.thymeleaf.IEngineConfiguration) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) TemplateResolution(org.thymeleaf.templateresolver.TemplateResolution) ITemplateResource(org.thymeleaf.templateresource.ITemplateResource) Test(org.junit.Test)

Example 2 with ITemplateResource

use of org.thymeleaf.templateresource.ITemplateResource in project thymeleaf-tests by thymeleaf.

the class TestTemplateResolver method resolveTemplate.

public TemplateResolution resolveTemplate(final IEngineConfiguration configuration, final String ownerTemplate, final String template, final Map<String, Object> templateResolutionAttributes) {
    final int placeholderPos = this.template.indexOf("{%%}");
    final String resource = this.template.substring(0, placeholderPos) + template + this.template.substring(placeholderPos + 4);
    final ITemplateResource templateResource = new StringTemplateResource(resource);
    final TemplateResolution templateResolution = new TemplateResolution(templateResource, // For the sake of these tests, considering resource existence verified is fine
    true, TemplateMode.HTML, false, new NonCacheableCacheEntryValidity());
    return templateResolution;
}
Also used : StringTemplateResource(org.thymeleaf.templateresource.StringTemplateResource) TemplateResolution(org.thymeleaf.templateresolver.TemplateResolution) ITemplateResource(org.thymeleaf.templateresource.ITemplateResource) NonCacheableCacheEntryValidity(org.thymeleaf.cache.NonCacheableCacheEntryValidity)

Example 3 with ITemplateResource

use of org.thymeleaf.templateresource.ITemplateResource in project sling by apache.

the class SlingTemplateResource method relative.

@Override
public ITemplateResource relative(final String relativeLocation) {
    final PathBuilder pathBuilder = new PathBuilder(resource.getPath());
    final String path = pathBuilder.append("..").append(relativeLocation).toString();
    final ResourceResolver resourceResolver = resource.getResourceResolver();
    final Resource relative = resourceResolver.getResource(path);
    // final Resource relative = resource.getParent().getChild(relativeLocation);
    return new SlingTemplateResource(relative);
}
Also used : PathBuilder(org.apache.sling.api.resource.path.PathBuilder) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) ITemplateResource(org.thymeleaf.templateresource.ITemplateResource) Resource(org.apache.sling.api.resource.Resource)

Example 4 with ITemplateResource

use of org.thymeleaf.templateresource.ITemplateResource in project thymeleaf by thymeleaf.

the class TemplateManager method parseStandalone.

/*
     * -------------
     * PARSE methods
     * -------------
     *
     * Parse methods will create 'template models' that are basically collections of events in the form of an
     * immutable IModel implementation.
     */
public TemplateModel parseStandalone(final ITemplateContext context, final String template, final Set<String> templateSelectors, final TemplateMode templateMode, final boolean useCache, final boolean failIfNotExists) {
    Validate.notNull(context, "Context cannot be null");
    Validate.notNull(template, "Template cannot be null");
    // templateSelectors CAN be null if we are going to render the entire template
    // templateMode CAN be null if we are going to use the mode specified by the template resolver
    // templateResolutionAttributes CAN be null
    final String ownerTemplate = context.getTemplateData().getTemplate();
    final Map<String, Object> templateResolutionAttributes = context.getTemplateResolutionAttributes();
    final Set<String> cleanTemplateSelectors;
    if (templateSelectors != null && !templateSelectors.isEmpty()) {
        Validate.containsNoEmpties(templateSelectors, "If specified, the Template Selector set cannot contain any nulls or empties");
        if (templateSelectors.size() == 1) {
            cleanTemplateSelectors = Collections.singleton(templateSelectors.iterator().next());
        } else {
            // We will be using a TreeSet because we want the selectors to be ORDERED, so that comparison at the
            // equals(...) method works alright
            cleanTemplateSelectors = Collections.unmodifiableSet(new TreeSet<String>(templateSelectors));
        }
    } else {
        cleanTemplateSelectors = null;
    }
    final TemplateCacheKey cacheKey = useCache ? new TemplateCacheKey(ownerTemplate, template, cleanTemplateSelectors, 0, 0, templateMode, templateResolutionAttributes) : null;
    /*
         * First look at the cache - it might be already cached
         */
    if (useCache && this.templateCache != null) {
        final TemplateModel cached = this.templateCache.get(cacheKey);
        if (cached != null) {
            /*
                 * Just at the end, and importantly AFTER CACHING, check if we need to apply any pre-processors
                 * to this model before returning and letting the engine insert the model in any way it needs.
                 */
            return applyPreProcessorsIfNeeded(context, cached);
        }
    }
    /*
         * Resolve the template
         */
    final TemplateResolution templateResolution = resolveTemplate(this.configuration, ownerTemplate, template, templateResolutionAttributes, failIfNotExists);
    /*
         * Once the template has been resolved (or tried to), and depending on the value of our 'failIfNotExists'
         * flag, we will check two conditions in which we will be returning null:
         *
         *    1. No template resolver has been able to resolve the template (this can happen if resolvers are
         *       configured with the 'checkExistence' flag to true).
         *    2. If the template was resolved, its existence should be checked in order to avoid exceptions during
         *       the reading phase.
         *
         * NOTE we will not cache this "null" result because the fact that a template is cacheable or not is
         * determined by template resolvers. And in this case there is no template resolver being applied
         * (actually, we are here because no resolver had success).
         */
    if (!failIfNotExists) {
        if (templateResolution == null) {
            // No resolver could resolve this
            return null;
        }
        if (!templateResolution.isTemplateResourceExistenceVerified()) {
            final ITemplateResource resource = templateResolution.getTemplateResource();
            if (resource == null || !resource.exists()) {
                // has not been cached (e.g. when it does not exist)
                return null;
            }
        }
    }
    /*
         * Build the TemplateData object
         */
    final TemplateData templateData = buildTemplateData(templateResolution, template, cleanTemplateSelectors, templateMode, useCache);
    /*
         *  Create the Template Handler that will be in charge of building the TemplateModel
         */
    final ModelBuilderTemplateHandler builderHandler = new ModelBuilderTemplateHandler(this.configuration, templateData);
    /*
         * PROCESS THE TEMPLATE
         */
    final ITemplateParser parser = getParserForTemplateMode(templateData.getTemplateMode());
    parser.parseStandalone(this.configuration, ownerTemplate, template, cleanTemplateSelectors, templateData.getTemplateResource(), templateData.getTemplateMode(), templateResolution.getUseDecoupledLogic(), builderHandler);
    final TemplateModel templateModel = builderHandler.getModel();
    /*
         * Cache the template if it is cacheable
         */
    if (useCache && this.templateCache != null) {
        if (templateResolution.getValidity().isCacheable()) {
            this.templateCache.put(cacheKey, templateModel);
        }
    }
    /*
         * Last step: just at the end, and importantly AFTER CACHING, check if we need to apply any pre-processors
         * to this model before returning and letting the engine insert the model in any way it needs.
         */
    return applyPreProcessorsIfNeeded(context, templateModel);
}
Also used : ITemplateParser(org.thymeleaf.templateparser.ITemplateParser) TemplateCacheKey(org.thymeleaf.cache.TemplateCacheKey) TreeSet(java.util.TreeSet) TemplateResolution(org.thymeleaf.templateresolver.TemplateResolution) ITemplateResource(org.thymeleaf.templateresource.ITemplateResource)

Example 5 with ITemplateResource

use of org.thymeleaf.templateresource.ITemplateResource in project thymeleaf by thymeleaf.

the class StandardMessageResolutionUtils method resolveMessagesForTemplate.

static Map<String, String> resolveMessagesForTemplate(final ITemplateResource templateResource, final Locale locale) {
    // Let the resource tell us about its 'base name'
    final String resourceBaseName = templateResource.getBaseName();
    if (resourceBaseName == null || resourceBaseName.length() == 0) {
        // No way to compute base name -> no messages
        return EMPTY_MESSAGES;
    }
    // Compute all the resource names we should use: *_gl_ES-gheada.properties, *_gl_ES.properties, _gl.properties...
    // The order here is important: as we will let values from more specific files overwrite those in less specific,
    // (e.g. a value for gl_ES will have more precedence than a value for gl). So we will iterate these resource
    // names from less specific to more specific.
    final List<String> messageResourceNames = computeMessageResourceNamesFromBase(resourceBaseName, locale);
    // Build the combined messages
    Map<String, String> combinedMessages = null;
    for (final String messageResourceName : messageResourceNames) {
        try {
            final ITemplateResource messageResource = templateResource.relative(messageResourceName);
            final Reader messageResourceReader = messageResource.reader();
            if (messageResourceReader != null) {
                final Properties messageProperties = readMessagesResource(messageResourceReader);
                if (messageProperties != null && !messageProperties.isEmpty()) {
                    if (combinedMessages == null) {
                        combinedMessages = new HashMap<String, String>(20);
                    }
                    for (final Map.Entry<Object, Object> propertyEntry : messageProperties.entrySet()) {
                        combinedMessages.put((String) propertyEntry.getKey(), (String) propertyEntry.getValue());
                    }
                }
            }
        } catch (final IOException ignored) {
        // File might not exist, simply try the next one
        }
    }
    if (combinedMessages == null) {
        return EMPTY_MESSAGES;
    }
    return Collections.unmodifiableMap(combinedMessages);
}
Also used : ITemplateResource(org.thymeleaf.templateresource.ITemplateResource) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException) Properties(java.util.Properties) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

ITemplateResource (org.thymeleaf.templateresource.ITemplateResource)12 TemplateResolution (org.thymeleaf.templateresolver.TemplateResolution)6 Map (java.util.Map)2 TreeSet (java.util.TreeSet)2 Resource (org.apache.sling.api.resource.Resource)2 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)2 IEngineConfiguration (org.thymeleaf.IEngineConfiguration)2 TemplateCacheKey (org.thymeleaf.cache.TemplateCacheKey)2 TemplateMode (org.thymeleaf.templatemode.TemplateMode)2 ITemplateParser (org.thymeleaf.templateparser.ITemplateParser)2 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 Reader (java.io.Reader)1 HashMap (java.util.HashMap)1 Locale (java.util.Locale)1 Properties (java.util.Properties)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 PathBuilder (org.apache.sling.api.resource.path.PathBuilder)1 SlingContext (org.apache.sling.scripting.thymeleaf.SlingContext)1 Test (org.junit.Test)1