/vertx-template-engines/vertx-web-templ-rocker/src/main/java/io/vertx/ext/web/templ/rocker/impl/RockerTemplateEngineImpl.java

https://github.com/vert-x3/vertx-web · Java · 60 lines · 34 code · 8 blank · 18 comment · 4 complexity · 544387cd7402dbf42e8407c1119b8da7 MD5 · raw file

  1. /*
  2. * Copyright 2014 Red Hat, Inc.
  3. *
  4. * All rights reserved. This program and the accompanying materials
  5. * are made available under the terms of the Eclipse Public License v1.0
  6. * and Apache License v2.0 which accompanies this distribution.
  7. *
  8. * The Eclipse Public License is available at
  9. * http://www.eclipse.org/legal/epl-v10.html
  10. *
  11. * The Apache License v2.0 is available at
  12. * http://www.opensource.org/licenses/apache2.0.php
  13. *
  14. * You may elect to redistribute this code under either of these licenses.
  15. */
  16. package io.vertx.ext.web.templ.rocker.impl;
  17. import com.fizzed.rocker.Rocker;
  18. import io.vertx.core.AsyncResult;
  19. import io.vertx.core.Future;
  20. import io.vertx.core.Handler;
  21. import io.vertx.core.buffer.Buffer;
  22. import io.vertx.ext.web.templ.rocker.RockerTemplateEngine;
  23. import java.util.Map;
  24. /**
  25. * @author <a href="mailto:xianguang.zhou@outlook.com">Xianguang Zhou</a>
  26. */
  27. public class RockerTemplateEngineImpl implements RockerTemplateEngine {
  28. private final String extension;
  29. public RockerTemplateEngineImpl(String extension) {
  30. this.extension = extension.charAt(0) == '.' ? extension : "." + extension;
  31. }
  32. @Override
  33. public void render(Map<String, Object> context, String templateFile, Handler<AsyncResult<Buffer>> handler) {
  34. try {
  35. handler.handle(Future.succeededFuture(
  36. Rocker.template(adjustLocation(templateFile))
  37. .relaxedBind(context)
  38. .render(VertxBufferOutput.FACTORY)
  39. .getBuffer()));
  40. } catch (final RuntimeException ex) {
  41. handler.handle(Future.failedFuture(ex));
  42. }
  43. }
  44. private String adjustLocation(String location) {
  45. if (extension != null) {
  46. if (!location.endsWith(extension)) {
  47. location += extension;
  48. }
  49. }
  50. return location;
  51. }
  52. }