private CharSequence iterableContext(Iterable<?> context, Options options) throws IOException {
    if (options.isFalsy(context)) {
      return options.inverse();
    }

    StringBuilder buffer = new StringBuilder();

    Iterator<?> iterator = reverse(context);
    int index = 0;
    Context parent = options.context;
    while (iterator.hasNext()) {
      Object element = iterator.next();

      boolean first = index == 0;
      boolean even = index % 2 == 0;
      boolean last = !iterator.hasNext();

      Context current =
          Context.newContext(parent, element)
              .data("index", index)
              .data("first", first ? "first" : "")
              .data("last", last ? "last" : "")
              .data("odd", even ? "" : "odd")
              .data("even", even ? "even" : "");
      buffer.append(options.fn(current));

      index++;
    }

    return buffer;
  }
Ejemplo n.º 2
0
  @Override
  public void execute() throws MojoExecutionException, MojoFailureException {
    File basedir = new File(prefix);
    TemplateLoader loader = new FileTemplateLoader(basedir, suffix);
    Handlebars handlebars = new Handlebars(loader);
    File output = new File(this.output);
    PrintWriter writer = null;
    boolean error = true;
    InputStream runtimeIS = getClass().getResourceAsStream("/handlebars.runtime.js");
    try {
      writer = new PrintWriter(output);
      if (includeRuntime) {
        IOUtil.copy(runtimeIS, writer);
      }
      List<File> files = FileUtils.getFiles(basedir, "/**/*" + suffix, null);
      getLog().info("Compiling templates...");
      getLog().debug("Options:");
      getLog().debug("  output: " + output);
      getLog().debug("  prefix: " + prefix);
      getLog().debug("  suffix: " + suffix);
      getLog().debug("  minimize: " + minimize);
      getLog().debug("  includeRuntime: " + includeRuntime);

      Context nullContext = Context.newContext(null);
      for (File file : files) {
        String templateName = file.getPath().replace(prefix, "").replace(suffix, "");
        if (templateName.startsWith("/")) {
          templateName = templateName.substring(1);
        }
        getLog().debug("compiling: " + templateName);
        Template template = handlebars.compileInline("{{precompile \"" + templateName + "\"}}");
        Options opts = new Options.Builder(handlebars, TagType.VAR, nullContext, template).build();

        writer.append("// Source: ").append(file.getPath()).append("\n");
        writer.append(PrecompileHelper.INSTANCE.apply(templateName, opts)).append("\n\n");
      }
      writer.flush();
      IOUtil.close(writer);
      if (minimize) {
        minimize(output);
      }
      if (files.size() > 0) {
        getLog().info("  templates were saved in: " + output);
        error = false;
      } else {
        getLog().warn("  no templates were found");
      }
    } catch (IOException ex) {
      throw new MojoFailureException("Can't scan directory " + basedir, ex);
    } finally {
      IOUtil.close(runtimeIS);
      IOUtil.close(writer);
      if (error) {
        output.delete();
      }
    }
  }
Ejemplo n.º 3
0
  @SuppressWarnings("unchecked")
  @Override
  protected void merge(final Context context, final Writer writer) throws IOException {
    if (body == null) {
      return;
    }
    final String helperName;
    Helper<Object> helper = helper(name);
    Template template = body;
    final Object childContext;
    Context currentScope = context;
    if (helper == null) {
      childContext = transform(context.get(name));
      if (inverted) {
        helperName = UnlessHelper.NAME;
      } else if (childContext instanceof Iterable) {
        helperName = EachHelper.NAME;
      } else if (childContext instanceof Boolean) {
        helperName = IfHelper.NAME;
      } else if (childContext instanceof Lambda) {
        helperName = WithHelper.NAME;
        template =
            Lambdas.compile(
                handlebars,
                (Lambda<Object, Object>) childContext,
                context,
                template,
                startDelimiter,
                endDelimiter);
      } else {
        helperName = WithHelper.NAME;
        currentScope = Context.newContext(context, childContext);
      }
      // A built-in helper might be override it.
      helper = handlebars.helper(helperName);
    } else {
      helperName = name;
      childContext = transform(determineContext(context));
    }
    Options options =
        new Options.Builder(handlebars, helperName, TagType.SECTION, currentScope, template)
            .setInverse(inverse == null ? Template.EMPTY : inverse)
            .setParams(params(currentScope))
            .setHash(hash(context))
            .build();
    options.data(Context.PARAM_SIZE, this.params.size());

    CharSequence result = helper.apply(childContext, options);
    if (!isEmpty(result)) {
      writer.append(result);
    }
  }
  private CharSequence hashContext(Object context, Options options) throws IOException {
    StringBuilder buffer = new StringBuilder();

    Context parent = options.context;
    Iterator<Map.Entry<String, Object>> iterator = reverse(options.propertySet(context));
    while (iterator.hasNext()) {
      Map.Entry<String, Object> entry = iterator.next();
      Context current = Context.newContext(parent, entry.getValue()).data("key", entry.getKey());
      buffer.append(options.fn(current));
    }

    return buffer;
  }
Ejemplo n.º 5
0
  @Override
  protected void doExecute() throws Exception {
    notNull(bundle, "The bundle's name parameter is required.");
    notNull(output, "The output parameter is required.");

    Handlebars handlebars = new Handlebars();
    Context context = Context.newContext(null);
    URL[] classpath = projectClasspath();

    new File(output).mkdirs();

    getLog().info("Converting bundles...");
    getLog().debug("Options:");
    getLog().debug("  output: " + output);
    getLog().debug("  merge: " + merge);
    getLog().debug("  amd: " + amd);
    getLog().debug("  classpath: " + join(classpath, File.pathSeparator));

    StringBuilder buffer = new StringBuilder();

    // 1. find all the bundles
    List<File> bundles = bundles(this.bundle, classpath);

    // 2. hash for i18njs helper
    Map<String, Object> hash = new HashMap<String, Object>();
    hash.put("wrap", false);
    if (classpath.length > 0) {
      hash.put("classLoader", new URLClassLoader(classpath, getClass().getClassLoader()));
    }
    // 3. get the base name from the bundle
    String basename = FileUtils.removePath(this.bundle.replace(".", "/"));

    Collections.sort(bundles);
    for (File bundle : bundles) {
      // bundle name
      String bundleName = FileUtils.removeExtension(bundle.getName());
      getLog().debug("converting: " + bundle.getName());
      // extract locale from bundle name
      String locale = bundleName.substring(basename.length());
      if (locale.startsWith("_")) {
        locale = locale.substring(1);
      }
      // set bundle name
      hash.put("bundle", this.bundle);

      Options options =
          new Options.Builder(handlebars, TagType.VAR, context, Template.EMPTY)
              .setHash(hash)
              .build();
      // convert to JS
      buffer.append(I18nHelper.i18nJs.apply(locale, options));

      if (!merge) {
        FileUtils.fileWrite(
            new File(output, bundleName + ".js"), encoding, wrap(bundleName, buffer, amd));
        buffer.setLength(0);
        getLog().debug("  => " + bundleName + ".js");
      } else {
        buffer.append("\n");
      }
    }
    if (merge && buffer.length() > 0) {
      FileUtils.fileWrite(new File(output, basename + ".js"), wrap(basename, buffer, amd));
      getLog().debug("  =>" + basename + ".js");
    }
  }