Search in sources :

Example 56 with Template

use of freemarker.template.Template in project deeplearning4j by deeplearning4j.

the class StaticPageUtil method renderHTMLContent.

public static String renderHTMLContent(Component... components) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    Configuration cfg = new Configuration(new Version(2, 3, 23));
    // Where do we load the templates from:
    cfg.setClassForTemplateLoading(StaticPageUtil.class, "");
    // Some other recommended settings:
    cfg.setIncompatibleImprovements(new Version(2, 3, 23));
    cfg.setDefaultEncoding("UTF-8");
    cfg.setLocale(Locale.US);
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    ClassPathResource cpr = new ClassPathResource("assets/dl4j-ui.js");
    String scriptContents = IOUtils.toString(cpr.getInputStream(), "UTF-8");
    Map<String, Object> pageElements = new HashMap<>();
    List<ComponentObject> list = new ArrayList<>();
    int i = 0;
    for (Component c : components) {
        list.add(new ComponentObject(String.valueOf(i), mapper.writeValueAsString(c)));
        i++;
    }
    pageElements.put("components", list);
    pageElements.put("scriptcontent", scriptContents);
    Template template = cfg.getTemplate("staticpage.ftl");
    Writer stringWriter = new StringWriter();
    template.process(pageElements, stringWriter);
    return stringWriter.toString();
}
Also used : Configuration(freemarker.template.Configuration) Template(freemarker.template.Template) StringWriter(java.io.StringWriter) Version(freemarker.template.Version) Component(org.deeplearning4j.ui.api.Component) ObjectMapper(org.nd4j.shade.jackson.databind.ObjectMapper) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 57 with Template

use of freemarker.template.Template in project ninja by ninjaframework.

the class TemplateEngineFreemarker method invoke.

@Override
public void invoke(Context context, Result result) {
    Object object = result.getRenderable();
    Map map;
    // if the object is null we simply render an empty map...
    if (object == null) {
        map = Maps.newHashMap();
    } else if (object instanceof Map) {
        map = (Map) object;
    } else {
        // We are getting an arbitrary Object and put that into
        // the root of freemarker
        // If you are rendering something like Results.ok().render(new MyObject())
        // Assume MyObject has a public String name field.            
        // You can then access the fields in the template like that:
        // ${myObject.publicField}            
        String realClassNameLowerCamelCase = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, object.getClass().getSimpleName());
        map = Maps.newHashMap();
        map.put(realClassNameLowerCamelCase, object);
    }
    // set language from framework. You can access
    // it in the templates as ${lang}
    Optional<String> language = lang.getLanguage(context, Optional.of(result));
    if (language.isPresent()) {
        map.put("lang", language.get());
    }
    // You can access the values by their key in the cookie
    if (!context.getSession().isEmpty()) {
        map.put("session", context.getSession().getData());
    }
    map.put("contextPath", context.getContextPath());
    map.put("validation", context.getValidation());
    //////////////////////////////////////////////////////////////////////
    // A method that renders i18n messages and can also render messages with 
    // placeholders directly in your template:
    // E.g.: ${i18n("mykey", myPlaceholderVariable)}
    //////////////////////////////////////////////////////////////////////
    map.put("i18n", new TemplateEngineFreemarkerI18nMethod(messages, context, result));
    Optional<String> requestLang = lang.getLanguage(context, Optional.of(result));
    Locale locale = lang.getLocaleFromStringOrDefault(requestLang);
    map.put("prettyTime", new TemplateEngineFreemarkerPrettyTimeMethod(locale));
    map.put("reverseRoute", templateEngineFreemarkerReverseRouteMethod);
    map.put("assetsAt", templateEngineFreemarkerAssetsAtMethod);
    map.put("webJarsAt", templateEngineFreemarkerWebJarsAtMethod);
    map.put("authenticityToken", new TemplateEngineFreemarkerAuthenticityTokenDirective(context));
    map.put("authenticityForm", new TemplateEngineFreemarkerAuthenticityFormDirective(context));
    ///////////////////////////////////////////////////////////////////////
    // Convenience method to translate possible flash scope keys.
    // !!! If you want to set messages with placeholders please do that
    // !!! in your controller. We only can set simple messages.
    // Eg. A message like "errorMessage=my name is: {0}" => translate in controller and pass directly.
    //     A message like " errorMessage=An error occurred" => use that as errorMessage.  
    //
    // get keys via ${flash.KEYNAME}
    //////////////////////////////////////////////////////////////////////
    Map<String, String> translatedFlashCookieMap = Maps.newHashMap();
    for (Entry<String, String> entry : context.getFlashScope().getCurrentFlashCookieData().entrySet()) {
        String messageValue = null;
        Optional<String> messageValueOptional = messages.get(entry.getValue(), context, Optional.of(result));
        if (!messageValueOptional.isPresent()) {
            messageValue = entry.getValue();
        } else {
            messageValue = messageValueOptional.get();
        }
        // new way
        translatedFlashCookieMap.put(entry.getKey(), messageValue);
    }
    // now we can retrieve flash cookie messages via ${flash.MESSAGE_KEY}
    map.put("flash", translatedFlashCookieMap);
    // Specify the data source where the template files come from.
    // Here I set a file directory for it:
    String templateName = templateEngineHelper.getTemplateForResult(context.getRoute(), result, this.fileSuffix);
    Template freemarkerTemplate = null;
    try {
        freemarkerTemplate = cfg.getTemplate(templateName);
        // Fully buffer the response so in the case of a template error we can 
        // return the applications 500 error message. Without fully buffering 
        // we can't guarantee we haven't flushed part of the response to the
        // client.
        StringWriter buffer = new StringWriter(64 * 1024);
        freemarkerTemplate.process(map, buffer);
        ResponseStreams responseStreams = context.finalizeHeaders(result);
        try (Writer writer = responseStreams.getWriter()) {
            writer.write(buffer.toString());
        }
    } catch (Exception cause) {
        // delegate rendering exception handling back to Ninja
        throwRenderingException(context, result, cause, templateName);
    }
}
Also used : Locale(java.util.Locale) TemplateEngineFreemarkerAuthenticityTokenDirective(ninja.template.directives.TemplateEngineFreemarkerAuthenticityTokenDirective) ResponseStreams(ninja.utils.ResponseStreams) TemplateEngineFreemarkerAuthenticityFormDirective(ninja.template.directives.TemplateEngineFreemarkerAuthenticityFormDirective) RenderingException(ninja.exceptions.RenderingException) TemplateException(freemarker.template.TemplateException) TemplateNotFoundException(freemarker.template.TemplateNotFoundException) IOException(java.io.IOException) ParseException(freemarker.core.ParseException) Template(freemarker.template.Template) StringWriter(java.io.StringWriter) Map(java.util.Map) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 58 with Template

use of freemarker.template.Template in project platformlayer by platformlayer.

the class TemplateEngine method runTemplate.

public void runTemplate(String templateName, Map<String, Object> model, Writer writer) throws MojoExecutionException, IOException {
    Template template;
    try {
        template = getTemplate(templateName);
    } catch (IOException e) {
        throw new MojoExecutionException("Error reading template: " + templateName, e);
    }
    try {
        template.process(model, writer);
    } catch (freemarker.template.TemplateException e) {
        throw new MojoExecutionException("Error running template: " + templateName, e);
    }
    writer.flush();
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) IOException(java.io.IOException) Template(freemarker.template.Template)

Example 59 with Template

use of freemarker.template.Template in project spring-framework by spring-projects.

the class FreeMarkerConfigurerTests method freeMarkerConfigurationFactoryBeanWithNonFileResourceLoaderPath.

@Test
@SuppressWarnings("rawtypes")
public void freeMarkerConfigurationFactoryBeanWithNonFileResourceLoaderPath() throws Exception {
    FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean();
    fcfb.setTemplateLoaderPath("file:/mydir");
    Properties settings = new Properties();
    settings.setProperty("localized_lookup", "false");
    fcfb.setFreemarkerSettings(settings);
    fcfb.setResourceLoader(new ResourceLoader() {

        @Override
        public Resource getResource(String location) {
            if (!("file:/mydir".equals(location) || "file:/mydir/test".equals(location))) {
                throw new IllegalArgumentException(location);
            }
            return new ByteArrayResource("test".getBytes(), "test");
        }

        @Override
        public ClassLoader getClassLoader() {
            return getClass().getClassLoader();
        }
    });
    fcfb.afterPropertiesSet();
    assertThat(fcfb.getObject(), instanceOf(Configuration.class));
    Configuration fc = fcfb.getObject();
    Template ft = fc.getTemplate("test");
    assertEquals("test", FreeMarkerTemplateUtils.processTemplateIntoString(ft, new HashMap()));
}
Also used : ResourceLoader(org.springframework.core.io.ResourceLoader) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader) FreeMarkerConfigurationFactoryBean(org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean) Configuration(freemarker.template.Configuration) HashMap(java.util.HashMap) FileSystemResource(org.springframework.core.io.FileSystemResource) ByteArrayResource(org.springframework.core.io.ByteArrayResource) Resource(org.springframework.core.io.Resource) ByteArrayResource(org.springframework.core.io.ByteArrayResource) Properties(java.util.Properties) Template(freemarker.template.Template) Test(org.junit.Test)

Example 60 with Template

use of freemarker.template.Template in project platformlayer by platformlayer.

the class FreemarkerTemplateEngine method runTemplate.

@Override
public void runTemplate(String templateName, Map<String, Object> model, Writer writer) throws TemplateException, IOException {
    Template template;
    try {
        template = getTemplate(templateName);
    } catch (IOException e) {
        throw new TemplateException("Error reading template: " + templateName, e);
    }
    try {
        template.process(model, writer);
    } catch (freemarker.template.TemplateException e) {
        throw new TemplateException("Error running template: " + templateName, e);
    }
    writer.flush();
}
Also used : IOException(java.io.IOException) Template(freemarker.template.Template)

Aggregations

Template (freemarker.template.Template)81 StringWriter (java.io.StringWriter)35 IOException (java.io.IOException)34 Configuration (freemarker.template.Configuration)33 HashMap (java.util.HashMap)28 Writer (java.io.Writer)27 TemplateException (freemarker.template.TemplateException)24 OutputStreamWriter (java.io.OutputStreamWriter)13 File (java.io.File)9 Map (java.util.Map)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 SimpleHash (freemarker.template.SimpleHash)6 JSONObject (org.json.JSONObject)6 DefaultObjectWrapper (freemarker.template.DefaultObjectWrapper)5 ThirdEyeAnomalyConfiguration (com.linkedin.thirdeye.anomaly.ThirdEyeAnomalyConfiguration)4 StringTemplateLoader (freemarker.cache.StringTemplateLoader)4 Environment (freemarker.core.Environment)4 BufferedWriter (java.io.BufferedWriter)4 FileOutputStream (java.io.FileOutputStream)4 StringReader (java.io.StringReader)4