samskivert / jmustache

A Java implementation of the Mustache templating language.
Other
834 stars 128 forks source link

Consider adding '-middle' special variable #114

Closed pacifico closed 4 years ago

pacifico commented 4 years ago

First, thanks for creating this wonderful code.

I would like the ability to transform lists of strings in the following way: ["bacon", "lettuce", "tomato"] -> "bacon, lettuce, and tomato" ["yin", "yang"] -> "yin and yang" ["only"] -> "only"

I couldn't quite get there using just -first and -last. Looking at the source code, it occurred to me adding a -middle special variable could make this possible.

diff --git a/src/main/java/com/samskivert/mustache/Template.java b/src/main/java/com/samskivert/mustache/Template.java
index bae9935..3944521 100644
--- a/src/main/java/com/samskivert/mustache/Template.java
+++ b/src/main/java/com/samskivert/mustache/Template.java
@@ -220,6 +220,8 @@ public class Template {
             return ctx.onFirst;
         } else if (name.equals(LAST_NAME)) {
             return ctx.onLast;
+        } else if (name.equals(MIDDLE_NAME)) {
+            return ((!ctx.onFirst) && (!ctx.onLast));
         } else if (name.equals(INDEX_NAME)) {
             return ctx.index;
         }
@@ -425,6 +427,7 @@ public class Template {
     protected static final String THIS_NAME = "this";
     protected static final String FIRST_NAME = "-first";
     protected static final String LAST_NAME = "-last";
+    protected static final String MIDDLE_NAME = "-middle";
     protected static final String INDEX_NAME = "-index";

     /** A fetcher cached for lookups that failed to find a fetcher. */
diff --git a/src/test/java/com/samskivert/mustache/SharedTests.java b/src/test/java/com/samskivert/mustache/SharedTests.java
index c4b3cae..1bf9fae 100644
--- a/src/test/java/com/samskivert/mustache/SharedTests.java
+++ b/src/test/java/com/samskivert/mustache/SharedTests.java
@@ -455,6 +455,11 @@ public abstract class SharedTests extends GWTTestCase
              context("things", Arrays.asList("foo")));
     }

+    @Test public void testMiddle () {
+        test("foo|bar|baz", "{{#things}}{{#-middle}}|{{/-middle}}{{this}}{{#-last}}|{{/-middle}}{{/things}}",
+             context("things", Arrays.asList("foo", "bar", "baz")));
+    }
+
     @Test public void testIndex () {
         test("123", "{{#things}}{{-index}}{{/things}}",
              context("things", Arrays.asList("foo", "bar", "baz")));

Thoughts?

pacifico commented 4 years ago

On further reflection, adding this would not enable me to solve my problem and I should not have posted this issue.