From 9cc19a425a9959f188ddff47c59bffbdd11673c7 Mon Sep 17 00:00:00 2001 From: Sam Pullara Date: Wed, 26 Jun 2024 16:01:23 -0700 Subject: [PATCH] update to latest spec tests --- .../com/github/mustachejava/SpecTest.java | 5 +- .../test/resources/spec/specs/comments.json | 12 + .../test/resources/spec/specs/comments.yml | 6 + .../resources/spec/specs/interpolation.yml | 6 + .../test/resources/spec/specs/partials.json | 14 + .../test/resources/spec/specs/partials.yml | 7 + .../test/resources/spec/specs/sections.json | 58 ++- .../test/resources/spec/specs/sections.yml | 44 +- .../resources/spec/specs/~dynamic-names.json | 316 +++++++++++++++ .../resources/spec/specs/~dynamic-names.yml | 377 ++++++++++++++++++ .../resources/spec/specs/~inheritance.json | 56 +++ .../resources/spec/specs/~inheritance.yml | 89 +++++ .../test/resources/spec/specs/~lambdas.json | 30 +- .../test/resources/spec/specs/~lambdas.yml | 10 + 14 files changed, 1011 insertions(+), 19 deletions(-) create mode 100644 compiler/src/test/resources/spec/specs/~dynamic-names.json create mode 100644 compiler/src/test/resources/spec/specs/~dynamic-names.yml diff --git a/compiler/src/test/java/com/github/mustachejava/SpecTest.java b/compiler/src/test/java/com/github/mustachejava/SpecTest.java index 4465d66b4..322cff167 100644 --- a/compiler/src/test/java/com/github/mustachejava/SpecTest.java +++ b/compiler/src/test/java/com/github/mustachejava/SpecTest.java @@ -12,6 +12,7 @@ import java.io.StringReader; import java.io.StringWriter; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.function.Function; @@ -101,7 +102,9 @@ public String apply(String input) { StringWriter writer = new StringWriter(); String json = data.toString(); if (json.startsWith("{")) { - compile.execute(writer, new Object[]{new ObjectMapper().readValue(json, Map.class), functionMap.get(file)}); + compile.execute(writer, new Object[]{functionMap.get(file), new ObjectMapper().readValue(json, Map.class)}); + } else if (json.startsWith("[")) { + compile.execute(writer, new Object[]{functionMap.get(file), new ObjectMapper().readValue(json, List.class)}); } else { String s = new ObjectMapper().readValue(json, String.class); compile.execute(writer, new Object[]{functionMap.get(file), s}); diff --git a/compiler/src/test/resources/spec/specs/comments.json b/compiler/src/test/resources/spec/specs/comments.json index 60a49292c..924ed468c 100644 --- a/compiler/src/test/resources/spec/specs/comments.json +++ b/compiler/src/test/resources/spec/specs/comments.json @@ -89,6 +89,18 @@ }, "template": "12345 {{! Comment Block! }} 67890", "expected": "12345 67890" + }, + { + "name": "Variable Name Collision", + "desc": "Comments must never render, even if variable with same name exists.", + "data": { + "! comment": 1, + "! comment ": 2, + "!comment": 3, + "comment": 4 + }, + "template": "comments never show: >{{! comment }}<", + "expected": "comments never show: ><" } ] } diff --git a/compiler/src/test/resources/spec/specs/comments.yml b/compiler/src/test/resources/spec/specs/comments.yml index 7b14c7f32..3bad09f61 100644 --- a/compiler/src/test/resources/spec/specs/comments.yml +++ b/compiler/src/test/resources/spec/specs/comments.yml @@ -101,3 +101,9 @@ tests: data: { } template: '12345 {{! Comment Block! }} 67890' expected: '12345 67890' + + - name: Variable Name Collision + desc: Comments must never render, even if variable with same name exists. + data: { '! comment': 1, '! comment ': 2, '!comment': 3, 'comment': 4} + template: 'comments never show: >{{! comment }}<' + expected: 'comments never show: ><' diff --git a/compiler/src/test/resources/spec/specs/interpolation.yml b/compiler/src/test/resources/spec/specs/interpolation.yml index aae2cf472..c2fe8d136 100644 --- a/compiler/src/test/resources/spec/specs/interpolation.yml +++ b/compiler/src/test/resources/spec/specs/interpolation.yml @@ -41,6 +41,12 @@ tests: expected: | Hello, world! + - name: No Re-interpolation + desc: Interpolated tag output should not be re-interpolated. + data: { template: '{{planet}}', planet: 'Earth' } + template: '{{template}}: {{planet}}' + expected: '{{planet}}: Earth' + - name: HTML Escaping desc: Basic interpolation should be HTML escaped. data: { forbidden: '& " < >' } diff --git a/compiler/src/test/resources/spec/specs/partials.json b/compiler/src/test/resources/spec/specs/partials.json index 89dde4647..cea9a963f 100644 --- a/compiler/src/test/resources/spec/specs/partials.json +++ b/compiler/src/test/resources/spec/specs/partials.json @@ -55,6 +55,20 @@ }, "expected": "X>" }, + { + "name": "Nested", + "desc": "The greater-than operator should work from within partials.", + "data": { + "a": "hello", + "b": "world" + }, + "template": "{{>outer}}", + "partials": { + "outer": "*{{a}} {{>inner}}*", + "inner": "{{b}}!" + }, + "expected": "*hello world!*" + }, { "name": "Surrounding Whitespace", "desc": "The greater-than operator should not alter surrounding whitespace.", diff --git a/compiler/src/test/resources/spec/specs/partials.yml b/compiler/src/test/resources/spec/specs/partials.yml index 8c415439f..11b33ee81 100644 --- a/compiler/src/test/resources/spec/specs/partials.yml +++ b/compiler/src/test/resources/spec/specs/partials.yml @@ -42,6 +42,13 @@ tests: partials: { node: '{{content}}<{{#nodes}}{{>node}}{{/nodes}}>' } expected: 'X>' + - name: Nested + desc: The greater-than operator should work from within partials. + data: { a: "hello", b: "world" } + template: '{{>outer}}' + partials: { outer: '*{{a}} {{>inner}}*', inner: '{{b}}!' } + expected: '*hello world!*' + # Whitespace Sensitivity - name: Surrounding Whitespace diff --git a/compiler/src/test/resources/spec/specs/sections.json b/compiler/src/test/resources/spec/specs/sections.json index 3acc414d4..d5555dad9 100644 --- a/compiler/src/test/resources/spec/specs/sections.json +++ b/compiler/src/test/resources/spec/specs/sections.json @@ -1,6 +1,6 @@ { "__ATTN__": "Do not edit this file; changes belong in the appropriate YAML file.", - "overview": "Section tags and End Section tags are used in combination to wrap a section\nof the template for iteration\n\nThese tags' content MUST be a non-whitespace character sequence NOT\ncontaining the current closing delimiter; each Section tag MUST be followed\nby an End Section tag with the same content within the same section.\n\nThis tag's content names the data to replace the tag. Name resolution is as\nfollows:\n 1) Split the name on periods; the first part is the name to resolve, any\n remaining parts should be retained.\n 2) Walk the context stack from top to bottom, finding the first context\n that is a) a hash containing the name as a key OR b) an object responding\n to a method with the given name.\n 3) If the context is a hash, the data is the value associated with the\n name.\n 4) If the context is an object and the method with the given name has an\n arity of 1, the method SHOULD be called with a String containing the\n unprocessed contents of the sections; the data is the value returned.\n 5) Otherwise, the data is the value returned by calling the method with\n the given name.\n 6) If any name parts were retained in step 1, each should be resolved\n against a context stack containing only the result from the former\n resolution. If any part fails resolution, the result should be considered\n falsey, and should interpolate as the empty string.\nIf the data is not of a list type, it is coerced into a list as follows: if\nthe data is truthy (e.g. `!!data == true`), use a single-element list\ncontaining the data, otherwise use an empty list.\n\nFor each element in the data list, the element MUST be pushed onto the\ncontext stack, the section MUST be rendered, and the element MUST be popped\noff the context stack.\n\nSection and End Section tags SHOULD be treated as standalone when\nappropriate.\n", + "overview": "Section tags and End Section tags are used in combination to wrap a section\nof the template for iteration.\n\nThese tags' content MUST be a non-whitespace character sequence NOT\ncontaining the current closing delimiter; each Section tag MUST be followed\nby an End Section tag with the same content within the same section.\n\nThis tag's content names the data to replace the tag. Name resolution is as\nfollows:\n 1) If the name is a single period (.), the data is the item currently\n sitting atop the context stack. Skip the rest of these steps.\n 2) Split the name on periods; the first part is the name to resolve, any\n remaining parts should be retained.\n 3) Walk the context stack from top to bottom, finding the first context\n that is a) a hash containing the name as a key OR b) an object responding\n to a method with the given name.\n 4) If the context is a hash, the data is the value associated with the\n name.\n 5) If the context is an object and the method with the given name has an\n arity of 1, the method SHOULD be called with a String containing the\n unprocessed contents of the sections; the data is the value returned.\n 6) Otherwise, the data is the value returned by calling the method with\n the given name.\n 7) If any name parts were retained in step 1, each should be resolved\n against a context stack containing only the result from the former\n resolution. If any part fails resolution, the result should be considered\n falsey, and should interpolate as the empty string.\n\nIf the data is not of a list type, it is coerced into a list as follows: if\nthe data is truthy (e.g. `!!data == true`), use a single-element list\ncontaining the data, otherwise use an empty list.\n\nFor each element in the data list, the element MUST be pushed onto the\ncontext stack, the section MUST be rendered, and the element MUST be popped\noff the context stack.\n\nSection and End Section tags SHOULD be treated as standalone when\nappropriate.\n", "tests": [ { "name": "Truthy", @@ -246,6 +246,62 @@ "template": "\"{{#list}}({{#.}}{{.}}{{/.}}){{/list}}\"", "expected": "\"(123)(abc)\"" }, + { + "name": "Implicit Iterator - HTML Escaping", + "desc": "Implicit iterators with basic interpolation should be HTML escaped.", + "data": { + "list": [ + "&", + "\"", + "<", + ">" + ] + }, + "template": "\"{{#list}}({{.}}){{/list}}\"", + "expected": "\"(&)(")(<)(>)\"" + }, + { + "name": "Implicit Iterator - Triple mustache", + "desc": "Implicit iterators in triple mustache should interpolate without HTML escaping.", + "data": { + "list": [ + "&", + "\"", + "<", + ">" + ] + }, + "template": "\"{{#list}}({{{.}}}){{/list}}\"", + "expected": "\"(&)(\")(<)(>)\"" + }, + { + "name": "Implicit Iterator - Ampersand", + "desc": "Implicit iterators in an Ampersand tag should interpolate without HTML escaping.", + "data": { + "list": [ + "&", + "\"", + "<", + ">" + ] + }, + "template": "\"{{#list}}({{&.}}){{/list}}\"", + "expected": "\"(&)(\")(<)(>)\"" + }, + { + "name": "Implicit Iterator - Root-level", + "desc": "Implicit iterators should work on root-level lists.", + "data": [ + { + "value": "a" + }, + { + "value": "b" + } + ], + "template": "\"{{#.}}({{value}}){{/.}}\"", + "expected": "\"(a)(b)\"" + }, { "name": "Dotted Names - Truthy", "desc": "Dotted names should be valid for Section tags.", diff --git a/compiler/src/test/resources/spec/specs/sections.yml b/compiler/src/test/resources/spec/specs/sections.yml index fdfd79952..741621e02 100644 --- a/compiler/src/test/resources/spec/specs/sections.yml +++ b/compiler/src/test/resources/spec/specs/sections.yml @@ -1,6 +1,6 @@ overview: | Section tags and End Section tags are used in combination to wrap a section - of the template for iteration + of the template for iteration. These tags' content MUST be a non-whitespace character sequence NOT containing the current closing delimiter; each Section tag MUST be followed @@ -8,22 +8,25 @@ overview: | This tag's content names the data to replace the tag. Name resolution is as follows: - 1) Split the name on periods; the first part is the name to resolve, any + 1) If the name is a single period (.), the data is the item currently + sitting atop the context stack. Skip the rest of these steps. + 2) Split the name on periods; the first part is the name to resolve, any remaining parts should be retained. - 2) Walk the context stack from top to bottom, finding the first context + 3) Walk the context stack from top to bottom, finding the first context that is a) a hash containing the name as a key OR b) an object responding to a method with the given name. - 3) If the context is a hash, the data is the value associated with the + 4) If the context is a hash, the data is the value associated with the name. - 4) If the context is an object and the method with the given name has an + 5) If the context is an object and the method with the given name has an arity of 1, the method SHOULD be called with a String containing the unprocessed contents of the sections; the data is the value returned. - 5) Otherwise, the data is the value returned by calling the method with + 6) Otherwise, the data is the value returned by calling the method with the given name. - 6) If any name parts were retained in step 1, each should be resolved + 7) If any name parts were retained in step 1, each should be resolved against a context stack containing only the result from the former resolution. If any part fails resolution, the result should be considered falsey, and should interpolate as the empty string. + If the data is not of a list type, it is coerced into a list as follows: if the data is truthy (e.g. `!!data == true`), use a single-element list containing the data, otherwise use an empty list. @@ -206,6 +209,33 @@ tests: template: '"{{#list}}({{#.}}{{.}}{{/.}}){{/list}}"' expected: '"(123)(abc)"' + - name: Implicit Iterator - HTML Escaping + desc: Implicit iterators with basic interpolation should be HTML escaped. + data: + list: [ '&', '"', '<', '>' ] + template: '"{{#list}}({{.}}){{/list}}"' + expected: '"(&)(")(<)(>)"' + + - name: Implicit Iterator - Triple mustache + desc: Implicit iterators in triple mustache should interpolate without HTML escaping. + data: + list: [ '&', '"', '<', '>' ] + template: '"{{#list}}({{{.}}}){{/list}}"' + expected: '"(&)(")(<)(>)"' + + - name: Implicit Iterator - Ampersand + desc: Implicit iterators in an Ampersand tag should interpolate without HTML escaping. + data: + list: [ '&', '"', '<', '>' ] + template: '"{{#list}}({{&.}}){{/list}}"' + expected: '"(&)(")(<)(>)"' + + - name: Implicit Iterator - Root-level + desc: Implicit iterators should work on root-level lists. + data: [ { value: 'a' }, { value: 'b' } ] + template: '"{{#.}}({{value}}){{/.}}"' + expected: '"(a)(b)"' + # Dotted Names - name: Dotted Names - Truthy diff --git a/compiler/src/test/resources/spec/specs/~dynamic-names.json b/compiler/src/test/resources/spec/specs/~dynamic-names.json new file mode 100644 index 000000000..b1faca6d9 --- /dev/null +++ b/compiler/src/test/resources/spec/specs/~dynamic-names.json @@ -0,0 +1,316 @@ +{ + "__ATTN__": "Do not edit this file; changes belong in the appropriate YAML file.", + "overview": "Rationale: this special notation was introduced primarily to allow the dynamic\nloading of partials. The main advantage that this notation offers is to allow\ndynamic loading of partials, which is particularly useful in cases where\npolymorphic data needs to be rendered in different ways. Such cases would\notherwise be possible to render only with solutions that are convoluted,\ninefficient, or both.\n\nExample.\nLet's consider the following data:\n\n items: [\n { content: 'Hello, World!' },\n { url: 'http://example.com/foo.jpg' },\n { content: 'Some text' },\n { content: 'Some other text' },\n { url: 'http://example.com/bar.jpg' },\n { url: 'http://example.com/baz.jpg' },\n { content: 'Last text here' }\n ]\n\nThe goal is to render the different types of items in different ways. The\nitems having a key named `content` should be rendered with the template\n`text.mustache`:\n\n {{!text.mustache}}\n {{content}}\n\nAnd the items having a key named `url` should be rendered with the template\n`image.mustache`:\n\n {{!image.mustache}}\n \n\nThere are already several ways to achieve this goal, here below are\nillustrated and discussed the most significant solutions to this problem.\n\nUsing Pre-Processing\n\nThe idea is to use a secondary templating mechanism to dynamically generate\nthe template that will be rendered.\nThe template that our secondary templating mechanism generates might look\nlike this:\n\n {{!template.mustache}}\n {{items.1.content}}\n \n {{items.3.content}}\n {{items.4.content}}\n \n \n {{items.7.content}}\n\nThis solutions offers the advantages of having more control over the template\nand minimizing the template blocks to the essential ones.\nThe drawbacks are the rendering speed and the complexity that the secondary\ntemplating mechanism requires.\n\nUsing Lambdas\n\nThe idea is to inject functions into the data that will be later called from\nthe template.\nThis way the data will look like this:\n\n items: [\n {\n content: 'Hello, World!',\n html: function() { return '{{>text}}'; }\n },\n {\n url: 'http://example.com/foo.jpg',\n html: function() { return '{{>image}}'; }\n },\n {\n content: 'Some text',\n html: function() { return '{{>text}}'; }\n },\n {\n content: 'Some other text',\n html: function() { return '{{>text}}'; }\n },\n {\n url: 'http://example.com/bar.jpg',\n html: function() { return '{{>image}}'; }\n },\n {\n url: 'http://example.com/baz.jpg',\n html: function() { return '{{>image}}'; }\n },\n {\n content: 'Last text here',\n html: function() { return '{{>text}}'; }\n }\n ]\n\nAnd the template will look like this:\n\n {{!template.mustache}}\n {{#items}}\n {{{html}}}\n {{/items}}\n\nThe advantage this solution offers is to have a light main template.\nThe drawback is that the data needs to embed logic and template tags in\nit.\n\nUsing If-Else Blocks\n\nThe idea is to put some logic into the main template so it can select the\ntemplates at rendering time:\n\n {{!template.mustache}}\n {{#items}}\n {{#url}}\n {{>image}}\n {{/url}}\n {{#content}}\n {{>text}}\n {{/content}}\n {{/items}}\n\nThe main advantage of this solution is that it works without adding any\noverhead fields to the data. It also documents which external templates are\nappropriate for expansion in this position.\nThe drawback is that this solution isn't optimal for heterogeneous data sets\nas the main template grows linearly with the number of polymorphic variants.\n\nUsing Dynamic Names\n\nThis is the solution proposed by this spec.\nThe idea is to load partials dynamically.\nThis way the data items have to be tagged with the corresponding partial name:\n\n items: [\n { content: 'Hello, World!', dynamic: 'text' },\n { url: 'http://example.com/foo.jpg', dynamic: 'image' },\n { content: 'Some text', dynamic: 'text' },\n { content: 'Some other text', dynamic: 'text' },\n { url: 'http://example.com/bar.jpg', dynamic: 'image' },\n { url: 'http://example.com/baz.jpg', dynamic: 'image' },\n { content: 'Last text here', dynamic: 'text' }\n ]\n\nAnd the template would simple look like this:\n\n {{!template.mustache}}\n {{#items}}\n {{>*dynamic}}\n {{/items}}\n\nSummary:\n\n +----------------+---------------------+-----------------------------------+\n | Approach | Pros | Cons |\n +----------------+---------------------+-----------------------------------+\n | Pre-Processing | Essential template, | Secondary templating system |\n | | more control | needed, slower rendering |\n | Lambdas | Slim template | Data tagging, logic in data |\n | If Blocks | No data overhead, | Template linear growth |\n | | self-documenting | |\n | Dynamic Names | Slim template | Data tagging |\n +----------------+---------------------+-----------------------------------+\n\nDynamic Names are a special notation to dynamically determine a tag's content.\n\nDynamic Names MUST be a non-whitespace character sequence NOT containing\nthe current closing delimiter. A Dynamic Name consists of an asterisk,\nfollowed by a dotted name. The dotted name follows the same notation as in an\nInterpolation tag.\n\nThis tag's dotted name, which is the Dynamic Name excluding the\nleading asterisk, references a key in the context whose value will be used in\nplace of the Dynamic Name itself as content of the tag. The dotted name\nresolution produces the same value as an Interpolation tag and does not affect\nthe context for further processing.\n\nSet Delimiter tags MUST NOT affect the resolution of a Dynamic Name. The\nDynamic Names MUST be resolved against the context stack local to the tag.\nFailed resolution of the dynamic name SHOULD result in nothing being rendered.\n\nEngines that implement Dynamic Names MUST support their use in Partial tags.\nIn engines that also implement the optional inheritance spec, Dynamic Names\ninside Parent tags SHOULD be supported as well. Dynamic Names cannot be\nresolved more than once (Dynamic Names cannot be nested).\n", + "tests": [ + { + "name": "Basic Behavior - Partial", + "desc": "The asterisk operator is used for dynamic partials.", + "data": { + "dynamic": "content" + }, + "template": "\"{{>*dynamic}}\"", + "partials": { + "content": "Hello, world!" + }, + "expected": "\"Hello, world!\"" + }, + { + "name": "Basic Behavior - Name Resolution", + "desc": "The asterisk is not part of the name that will be resolved in the context.\n", + "data": { + "dynamic": "content", + "*dynamic": "wrong" + }, + "template": "\"{{>*dynamic}}\"", + "partials": { + "content": "Hello, world!", + "wrong": "Invisible" + }, + "expected": "\"Hello, world!\"" + }, + { + "name": "Context Misses - Partial", + "desc": "Failed context lookups should be considered falsey.", + "data": { + }, + "template": "\"{{>*missing}}\"", + "partials": { + "missing": "Hello, world!" + }, + "expected": "\"\"" + }, + { + "name": "Failed Lookup - Partial", + "desc": "The empty string should be used when the named partial is not found.", + "data": { + "dynamic": "content" + }, + "template": "\"{{>*dynamic}}\"", + "partials": { + "foobar": "Hello, world!" + }, + "expected": "\"\"" + }, + { + "name": "Context", + "desc": "The dynamic partial should operate within the current context.", + "data": { + "text": "Hello, world!", + "example": "partial" + }, + "template": "\"{{>*example}}\"", + "partials": { + "partial": "*{{text}}*" + }, + "expected": "\"*Hello, world!*\"" + }, + { + "name": "Dotted Names", + "desc": "The dynamic partial should operate within the current context.", + "data": { + "text": "Hello, world!", + "foo": { + "bar": { + "baz": "partial" + } + } + }, + "template": "\"{{>*foo.bar.baz}}\"", + "partials": { + "partial": "*{{text}}*" + }, + "expected": "\"*Hello, world!*\"" + }, + { + "name": "Dotted Names - Operator Precedence", + "desc": "The dotted name should be resolved entirely before being dereferenced.", + "data": { + "text": "Hello, world!", + "foo": "test", + "test": { + "bar": { + "baz": "partial" + } + } + }, + "template": "\"{{>*foo.bar.baz}}\"", + "partials": { + "partial": "*{{text}}*" + }, + "expected": "\"\"" + }, + { + "name": "Dotted Names - Failed Lookup", + "desc": "The dynamic partial should operate within the current context.", + "data": { + "foo": { + "text": "Hello, world!", + "bar": { + "baz": "partial" + } + } + }, + "template": "\"{{>*foo.bar.baz}}\"", + "partials": { + "partial": "*{{text}}*" + }, + "expected": "\"**\"" + }, + { + "name": "Dotted names - Context Stacking", + "desc": "Dotted names should not push a new frame on the context stack.", + "data": { + "section1": { + "value": "section1" + }, + "section2": { + "dynamic": "partial", + "value": "section2" + } + }, + "template": "{{#section1}}{{>*section2.dynamic}}{{/section1}}", + "partials": { + "partial": "\"{{value}}\"" + }, + "expected": "\"section1\"" + }, + { + "name": "Dotted names - Context Stacking Under Repetition", + "desc": "Dotted names should not push a new frame on the context stack.", + "data": { + "value": "test", + "section1": [ + 1, + 2 + ], + "section2": { + "dynamic": "partial", + "value": "section2" + } + }, + "template": "{{#section1}}{{>*section2.dynamic}}{{/section1}}", + "partials": { + "partial": "{{value}}" + }, + "expected": "testtest" + }, + { + "name": "Dotted names - Context Stacking Failed Lookup", + "desc": "Dotted names should resolve against the proper context stack.", + "data": { + "section1": [ + 1, + 2 + ], + "section2": { + "dynamic": "partial", + "value": "section2" + } + }, + "template": "{{#section1}}{{>*section2.dynamic}}{{/section1}}", + "partials": { + "partial": "\"{{value}}\"" + }, + "expected": "\"\"\"\"" + }, + { + "name": "Recursion", + "desc": "Dynamic partials should properly recurse.", + "data": { + "template": "node", + "content": "X", + "nodes": [ + { + "content": "Y", + "nodes": [ + + ] + } + ] + }, + "template": "{{>*template}}", + "partials": { + "node": "{{content}}<{{#nodes}}{{>*template}}{{/nodes}}>" + }, + "expected": "X>" + }, + { + "name": "Dynamic Names - Double Dereferencing", + "desc": "Dynamic Names can't be dereferenced more than once.", + "data": { + "dynamic": "test", + "test": "content" + }, + "template": "\"{{>**dynamic}}\"", + "partials": { + "content": "Hello, world!" + }, + "expected": "\"\"" + }, + { + "name": "Dynamic Names - Composed Dereferencing", + "desc": "Dotted Names are resolved entirely before dereferencing begins.", + "data": { + "foo": "fizz", + "bar": "buzz", + "fizz": { + "buzz": { + "content": null + } + } + }, + "template": "\"{{>*foo.*bar}}\"", + "partials": { + "content": "Hello, world!" + }, + "expected": "\"\"" + }, + { + "name": "Surrounding Whitespace", + "desc": "A dynamic partial should not alter surrounding whitespace; any\nwhitespace preceding the tag should be treated as indentation while any\nwhitespace succeding the tag should be left untouched.\n", + "data": { + "partial": "foobar" + }, + "template": "| {{>*partial}} |", + "partials": { + "foobar": "\t|\t" + }, + "expected": "| \t|\t |" + }, + { + "name": "Inline Indentation", + "desc": "Whitespace should be left untouched: whitespaces preceding the tag\nshould be treated as indentation.\n", + "data": { + "dynamic": "partial", + "data": "|" + }, + "template": " {{data}} {{>*dynamic}}\n", + "partials": { + "partial": ">\n>" + }, + "expected": " | >\n>\n" + }, + { + "name": "Standalone Line Endings", + "desc": "\"\\r\\n\" should be considered a newline for standalone tags.", + "data": { + "dynamic": "partial" + }, + "template": "|\r\n{{>*dynamic}}\r\n|", + "partials": { + "partial": ">" + }, + "expected": "|\r\n>|" + }, + { + "name": "Standalone Without Previous Line", + "desc": "Standalone tags should not require a newline to precede them.", + "data": { + "dynamic": "partial" + }, + "template": " {{>*dynamic}}\n>", + "partials": { + "partial": ">\n>" + }, + "expected": " >\n >>" + }, + { + "name": "Standalone Without Newline", + "desc": "Standalone tags should not require a newline to follow them.", + "data": { + "dynamic": "partial" + }, + "template": ">\n {{>*dynamic}}", + "partials": { + "partial": ">\n>" + }, + "expected": ">\n >\n >" + }, + { + "name": "Standalone Indentation", + "desc": "Each line of the partial should be indented before rendering.", + "data": { + "dynamic": "partial", + "content": "<\n->" + }, + "template": "\\\n {{>*dynamic}}\n/\n", + "partials": { + "partial": "|\n{{{content}}}\n|\n" + }, + "expected": "\\\n |\n <\n->\n |\n/\n" + }, + { + "name": "Padding Whitespace", + "desc": "Superfluous in-tag whitespace should be ignored.", + "data": { + "dynamic": "partial", + "boolean": true + }, + "template": "|{{> * dynamic }}|", + "partials": { + "partial": "[]" + }, + "expected": "|[]|" + } + ] +} diff --git a/compiler/src/test/resources/spec/specs/~dynamic-names.yml b/compiler/src/test/resources/spec/specs/~dynamic-names.yml new file mode 100644 index 000000000..a9f5d0321 --- /dev/null +++ b/compiler/src/test/resources/spec/specs/~dynamic-names.yml @@ -0,0 +1,377 @@ +overview: | + Rationale: this special notation was introduced primarily to allow the dynamic + loading of partials. The main advantage that this notation offers is to allow + dynamic loading of partials, which is particularly useful in cases where + polymorphic data needs to be rendered in different ways. Such cases would + otherwise be possible to render only with solutions that are convoluted, + inefficient, or both. + + Example. + Let's consider the following data: + + items: [ + { content: 'Hello, World!' }, + { url: 'http://example.com/foo.jpg' }, + { content: 'Some text' }, + { content: 'Some other text' }, + { url: 'http://example.com/bar.jpg' }, + { url: 'http://example.com/baz.jpg' }, + { content: 'Last text here' } + ] + + The goal is to render the different types of items in different ways. The + items having a key named `content` should be rendered with the template + `text.mustache`: + + {{!text.mustache}} + {{content}} + + And the items having a key named `url` should be rendered with the template + `image.mustache`: + + {{!image.mustache}} + + + There are already several ways to achieve this goal, here below are + illustrated and discussed the most significant solutions to this problem. + + Using Pre-Processing + + The idea is to use a secondary templating mechanism to dynamically generate + the template that will be rendered. + The template that our secondary templating mechanism generates might look + like this: + + {{!template.mustache}} + {{items.1.content}} + + {{items.3.content}} + {{items.4.content}} + + + {{items.7.content}} + + This solutions offers the advantages of having more control over the template + and minimizing the template blocks to the essential ones. + The drawbacks are the rendering speed and the complexity that the secondary + templating mechanism requires. + + Using Lambdas + + The idea is to inject functions into the data that will be later called from + the template. + This way the data will look like this: + + items: [ + { + content: 'Hello, World!', + html: function() { return '{{>text}}'; } + }, + { + url: 'http://example.com/foo.jpg', + html: function() { return '{{>image}}'; } + }, + { + content: 'Some text', + html: function() { return '{{>text}}'; } + }, + { + content: 'Some other text', + html: function() { return '{{>text}}'; } + }, + { + url: 'http://example.com/bar.jpg', + html: function() { return '{{>image}}'; } + }, + { + url: 'http://example.com/baz.jpg', + html: function() { return '{{>image}}'; } + }, + { + content: 'Last text here', + html: function() { return '{{>text}}'; } + } + ] + + And the template will look like this: + + {{!template.mustache}} + {{#items}} + {{{html}}} + {{/items}} + + The advantage this solution offers is to have a light main template. + The drawback is that the data needs to embed logic and template tags in + it. + + Using If-Else Blocks + + The idea is to put some logic into the main template so it can select the + templates at rendering time: + + {{!template.mustache}} + {{#items}} + {{#url}} + {{>image}} + {{/url}} + {{#content}} + {{>text}} + {{/content}} + {{/items}} + + The main advantage of this solution is that it works without adding any + overhead fields to the data. It also documents which external templates are + appropriate for expansion in this position. + The drawback is that this solution isn't optimal for heterogeneous data sets + as the main template grows linearly with the number of polymorphic variants. + + Using Dynamic Names + + This is the solution proposed by this spec. + The idea is to load partials dynamically. + This way the data items have to be tagged with the corresponding partial name: + + items: [ + { content: 'Hello, World!', dynamic: 'text' }, + { url: 'http://example.com/foo.jpg', dynamic: 'image' }, + { content: 'Some text', dynamic: 'text' }, + { content: 'Some other text', dynamic: 'text' }, + { url: 'http://example.com/bar.jpg', dynamic: 'image' }, + { url: 'http://example.com/baz.jpg', dynamic: 'image' }, + { content: 'Last text here', dynamic: 'text' } + ] + + And the template would simple look like this: + + {{!template.mustache}} + {{#items}} + {{>*dynamic}} + {{/items}} + + Summary: + + +----------------+---------------------+-----------------------------------+ + | Approach | Pros | Cons | + +----------------+---------------------+-----------------------------------+ + | Pre-Processing | Essential template, | Secondary templating system | + | | more control | needed, slower rendering | + | Lambdas | Slim template | Data tagging, logic in data | + | If Blocks | No data overhead, | Template linear growth | + | | self-documenting | | + | Dynamic Names | Slim template | Data tagging | + +----------------+---------------------+-----------------------------------+ + + Dynamic Names are a special notation to dynamically determine a tag's content. + + Dynamic Names MUST be a non-whitespace character sequence NOT containing + the current closing delimiter. A Dynamic Name consists of an asterisk, + followed by a dotted name. The dotted name follows the same notation as in an + Interpolation tag. + + This tag's dotted name, which is the Dynamic Name excluding the + leading asterisk, references a key in the context whose value will be used in + place of the Dynamic Name itself as content of the tag. The dotted name + resolution produces the same value as an Interpolation tag and does not affect + the context for further processing. + + Set Delimiter tags MUST NOT affect the resolution of a Dynamic Name. The + Dynamic Names MUST be resolved against the context stack local to the tag. + Failed resolution of the dynamic name SHOULD result in nothing being rendered. + + Engines that implement Dynamic Names MUST support their use in Partial tags. + In engines that also implement the optional inheritance spec, Dynamic Names + inside Parent tags SHOULD be supported as well. Dynamic Names cannot be + resolved more than once (Dynamic Names cannot be nested). + +tests: + - name: Basic Behavior - Partial + desc: The asterisk operator is used for dynamic partials. + data: { dynamic: 'content' } + template: '"{{>*dynamic}}"' + partials: { content: 'Hello, world!' } + expected: '"Hello, world!"' + + - name: Basic Behavior - Name Resolution + desc: | + The asterisk is not part of the name that will be resolved in the context. + data: { dynamic: 'content', '*dynamic': 'wrong' } + template: '"{{>*dynamic}}"' + partials: { content: 'Hello, world!', wrong: 'Invisible' } + expected: '"Hello, world!"' + + - name: Context Misses - Partial + desc: Failed context lookups should be considered falsey. + data: { } + template: '"{{>*missing}}"' + partials: { missing: 'Hello, world!' } + expected: '""' + + - name: Failed Lookup - Partial + desc: The empty string should be used when the named partial is not found. + data: { dynamic: 'content' } + template: '"{{>*dynamic}}"' + partials: { foobar: 'Hello, world!' } + expected: '""' + + - name: Context + desc: The dynamic partial should operate within the current context. + data: { text: 'Hello, world!', example: 'partial' } + template: '"{{>*example}}"' + partials: { partial: '*{{text}}*' } + expected: '"*Hello, world!*"' + + - name: Dotted Names + desc: The dynamic partial should operate within the current context. + data: { text: 'Hello, world!', foo: { bar: { baz: 'partial' } } } + template: '"{{>*foo.bar.baz}}"' + partials: { partial: '*{{text}}*' } + expected: '"*Hello, world!*"' + + - name: Dotted Names - Operator Precedence + desc: The dotted name should be resolved entirely before being dereferenced. + data: + text: 'Hello, world!' + foo: 'test' + test: + bar: + baz: 'partial' + template: '"{{>*foo.bar.baz}}"' + partials: { partial: '*{{text}}*' } + expected: '""' + + - name: Dotted Names - Failed Lookup + desc: The dynamic partial should operate within the current context. + data: + foo: + text: 'Hello, world!' + bar: + baz: 'partial' + template: '"{{>*foo.bar.baz}}"' + partials: { partial: '*{{text}}*' } + expected: '"**"' + + - name: Dotted names - Context Stacking + desc: Dotted names should not push a new frame on the context stack. + data: + section1: { value: 'section1' } + section2: { dynamic: 'partial', value: 'section2' } + template: "{{#section1}}{{>*section2.dynamic}}{{/section1}}" + partials: + partial: '"{{value}}"' + expected: '"section1"' + + - name: Dotted names - Context Stacking Under Repetition + desc: Dotted names should not push a new frame on the context stack. + data: + value: 'test' + section1: [ 1, 2 ] + section2: { dynamic: 'partial', value: 'section2' } + template: "{{#section1}}{{>*section2.dynamic}}{{/section1}}" + partials: + partial: "{{value}}" + expected: "testtest" + + - name: Dotted names - Context Stacking Failed Lookup + desc: Dotted names should resolve against the proper context stack. + data: + section1: [ 1, 2 ] + section2: { dynamic: 'partial', value: 'section2' } + template: "{{#section1}}{{>*section2.dynamic}}{{/section1}}" + partials: + partial: '"{{value}}"' + expected: '""""' + + - name: Recursion + desc: Dynamic partials should properly recurse. + data: + template: 'node' + content: 'X' + nodes: [ { content: 'Y', nodes: [] } ] + template: '{{>*template}}' + partials: { node: '{{content}}<{{#nodes}}{{>*template}}{{/nodes}}>' } + expected: 'X>' + + - name: Dynamic Names - Double Dereferencing + desc: Dynamic Names can't be dereferenced more than once. + data: { dynamic: 'test', 'test': 'content' } + template: '"{{>**dynamic}}"' + partials: { content: 'Hello, world!' } + expected: '""' + + - name: Dynamic Names - Composed Dereferencing + desc: Dotted Names are resolved entirely before dereferencing begins. + data: { foo: 'fizz', bar: 'buzz', fizz: { buzz: { content: null } } } + template: '"{{>*foo.*bar}}"' + partials: { content: 'Hello, world!' } + expected: '""' + + # Whitespace Sensitivity + + - name: Surrounding Whitespace + desc: | + A dynamic partial should not alter surrounding whitespace; any + whitespace preceding the tag should be treated as indentation while any + whitespace succeding the tag should be left untouched. + data: { partial: 'foobar' } + template: '| {{>*partial}} |' + partials: { foobar: "\t|\t" } + expected: "| \t|\t |" + + - name: Inline Indentation + desc: | + Whitespace should be left untouched: whitespaces preceding the tag + should be treated as indentation. + data: { dynamic: 'partial', data: '|' } + template: " {{data}} {{>*dynamic}}\n" + partials: { partial: ">\n>" } + expected: " | >\n>\n" + + - name: Standalone Line Endings + desc: '"\r\n" should be considered a newline for standalone tags.' + data: { dynamic: 'partial' } + template: "|\r\n{{>*dynamic}}\r\n|" + partials: { partial: ">" } + expected: "|\r\n>|" + + - name: Standalone Without Previous Line + desc: Standalone tags should not require a newline to precede them. + data: { dynamic: 'partial' } + template: " {{>*dynamic}}\n>" + partials: { partial: ">\n>"} + expected: " >\n >>" + + - name: Standalone Without Newline + desc: Standalone tags should not require a newline to follow them. + data: { dynamic: 'partial' } + template: ">\n {{>*dynamic}}" + partials: { partial: ">\n>" } + expected: ">\n >\n >" + + - name: Standalone Indentation + desc: Each line of the partial should be indented before rendering. + data: { dynamic: 'partial', content: "<\n->" } + template: | + \ + {{>*dynamic}} + / + partials: + partial: | + | + {{{content}}} + | + expected: | + \ + | + < + -> + | + / + + # Whitespace Insensitivity + + - name: Padding Whitespace + desc: Superfluous in-tag whitespace should be ignored. + data: { dynamic: 'partial', boolean: true } + template: "|{{> * dynamic }}|" + partials: { partial: "[]" } + expected: '|[]|' diff --git a/compiler/src/test/resources/spec/specs/~inheritance.json b/compiler/src/test/resources/spec/specs/~inheritance.json index 0a6878bd8..608d55b87 100644 --- a/compiler/src/test/resources/spec/specs/~inheritance.json +++ b/compiler/src/test/resources/spec/specs/~inheritance.json @@ -245,6 +245,62 @@ "parent": "{{#nested}}{{$block}}You say {{fruit}}.{{/block}}{{/nested}}" }, "expected": "I say bananas." + }, + { + "name": "Standalone parent", + "desc": "A parent's opening and closing tags need not be on separate lines in order to be standalone", + "data": { + }, + "template": "Hi,\n {{ {{planet}}\"", "clojure": "(fn [] \"|planet| => {{planet}}\")", "lisp": "(lambda () \"|planet| => {{planet}}\")", - "pwsh": "\"|planet| => {{planet}}\"" + "pwsh": "\"|planet| => {{planet}}\"", + "go": "func() string { return \"|planet| => {{planet}}\" }" } }, "template": "{{= | | =}}\nHello, (|&lambda|)!", @@ -78,7 +81,8 @@ "python": "lambda: globals().update(calls=globals().get(\"calls\",0)+1) or calls", "clojure": "(def g (atom 0)) (fn [] (swap! g inc))", "lisp": "(let ((g 0)) (lambda () (incf g)))", - "pwsh": "if (($null -eq $script:calls) -or ($script:calls -ge 3)){$script:calls=0}; ++$script:calls; $script:calls" + "pwsh": "if (($null -eq $script:calls) -or ($script:calls -ge 3)){$script:calls=0}; ++$script:calls; $script:calls", + "go": "func() func() int { g := 0; return func() int { g++; return g } }()" } }, "template": "{{lambda}} == {{{lambda}}} == {{lambda}}", @@ -98,7 +102,8 @@ "python": "lambda: \">\"", "clojure": "(fn [] \">\")", "lisp": "(lambda () \">\")", - "pwsh": "\">\"" + "pwsh": "\">\"", + "go": "func() string { return \">\" }" } }, "template": "<{{lambda}}{{{lambda}}}", @@ -119,7 +124,8 @@ "python": "lambda text: text == \"{{x}}\" and \"yes\" or \"no\"", "clojure": "(fn [text] (if (= text \"{{x}}\") \"yes\" \"no\"))", "lisp": "(lambda (text) (if (string= text \"{{x}}\") \"yes\" \"no\"))", - "pwsh": "if ($args[0] -eq \"{{x}}\") {\"yes\"} else {\"no\"}" + "pwsh": "if ($args[0] -eq \"{{x}}\") {\"yes\"} else {\"no\"}", + "go": "func(text string) string { if text == \"{{x}}\" { return \"yes\" } else { return \"no\" } }" } }, "template": "<{{#lambda}}{{x}}{{/lambda}}>", @@ -140,7 +146,8 @@ "python": "lambda text: \"%s{{planet}}%s\" % (text, text)", "clojure": "(fn [text] (str text \"{{planet}}\" text))", "lisp": "(lambda (text) (format nil \"~a{{planet}}~a\" text text))", - "pwsh": "\"$($args[0]){{planet}}$($args[0])\"" + "pwsh": "\"$($args[0]){{planet}}$($args[0])\"", + "go": "func(text string) string { return text + \"{{planet}}\" + text }" } }, "template": "<{{#lambda}}-{{/lambda}}>", @@ -161,7 +168,8 @@ "python": "lambda text: \"%s{{planet}} => |planet|%s\" % (text, text)", "clojure": "(fn [text] (str text \"{{planet}} => |planet|\" text))", "lisp": "(lambda (text) (format nil \"~a{{planet}} => |planet|~a\" text text))", - "pwsh": "\"$($args[0]){{planet}} => |planet|$($args[0])\"" + "pwsh": "\"$($args[0]){{planet}} => |planet|$($args[0])\"", + "go": "func(text string) string { return text + \"{{planet}} => |planet|\" + text }" } }, "template": "{{= | | =}}<|#lambda|-|/lambda|>", @@ -181,7 +189,8 @@ "python": "lambda text: \"__%s__\" % (text)", "clojure": "(fn [text] (str \"__\" text \"__\"))", "lisp": "(lambda (text) (format nil \"__~a__\" text))", - "pwsh": "\"__$($args[0])__\"" + "pwsh": "\"__$($args[0])__\"", + "go": "func(text string) string { return \"__\" + text + \"__\" }" } }, "template": "{{#lambda}}FILE{{/lambda}} != {{#lambda}}LINE{{/lambda}}", @@ -202,7 +211,8 @@ "python": "lambda text: 0", "clojure": "(fn [text] false)", "lisp": "(lambda (text) (declare (ignore text)) nil)", - "pwsh": "$false" + "pwsh": "$false", + "go": "func(text string) bool { return false }" } }, "template": "<{{^lambda}}{{static}}{{/lambda}}>", diff --git a/compiler/src/test/resources/spec/specs/~lambdas.yml b/compiler/src/test/resources/spec/specs/~lambdas.yml index 2e3316b68..1122bf9cc 100644 --- a/compiler/src/test/resources/spec/specs/~lambdas.yml +++ b/compiler/src/test/resources/spec/specs/~lambdas.yml @@ -25,6 +25,7 @@ tests: clojure: '(fn [] "world")' lisp: '(lambda () "world")' pwsh: '"world"' + go: 'func() string { return "world" }' template: "Hello, {{lambda}}!" expected: "Hello, world!" @@ -42,6 +43,7 @@ tests: clojure: '(fn [] "{{planet}}")' lisp: '(lambda () "{{planet}}")' pwsh: '"{{planet}}"' + go: 'func() string { return "{{planet}}" }' template: "Hello, {{lambda}}!" expected: "Hello, world!" @@ -59,6 +61,7 @@ tests: clojure: '(fn [] "|planet| => {{planet}}")' lisp: '(lambda () "|planet| => {{planet}}")' pwsh: '"|planet| => {{planet}}"' + go: 'func() string { return "|planet| => {{planet}}" }' template: "{{= | | =}}\nHello, (|&lambda|)!" expected: "Hello, (|planet| => world)!" @@ -75,6 +78,7 @@ tests: clojure: '(def g (atom 0)) (fn [] (swap! g inc))' lisp: '(let ((g 0)) (lambda () (incf g)))' pwsh: 'if (($null -eq $script:calls) -or ($script:calls -ge 3)){$script:calls=0}; ++$script:calls; $script:calls' + go: 'func() func() int { g := 0; return func() int { g++; return g } }()' template: '{{lambda}} == {{{lambda}}} == {{lambda}}' expected: '1 == 2 == 3' @@ -91,6 +95,7 @@ tests: clojure: '(fn [] ">")' lisp: '(lambda () ">")' pwsh: '">"' + go: 'func() string { return ">" }' template: "<{{lambda}}{{{lambda}}}" expected: "<>>" @@ -108,6 +113,7 @@ tests: clojure: '(fn [text] (if (= text "{{x}}") "yes" "no"))' lisp: '(lambda (text) (if (string= text "{{x}}") "yes" "no"))' pwsh: 'if ($args[0] -eq "{{x}}") {"yes"} else {"no"}' + go: 'func(text string) string { if text == "{{x}}" { return "yes" } else { return "no" } }' template: "<{{#lambda}}{{x}}{{/lambda}}>" expected: "" @@ -125,6 +131,7 @@ tests: clojure: '(fn [text] (str text "{{planet}}" text))' lisp: '(lambda (text) (format nil "~a{{planet}}~a" text text))' pwsh: '"$($args[0]){{planet}}$($args[0])"' + go: 'func(text string) string { return text + "{{planet}}" + text }' template: "<{{#lambda}}-{{/lambda}}>" expected: "<-Earth->" @@ -142,6 +149,7 @@ tests: clojure: '(fn [text] (str text "{{planet}} => |planet|" text))' lisp: '(lambda (text) (format nil "~a{{planet}} => |planet|~a" text text))' pwsh: '"$($args[0]){{planet}} => |planet|$($args[0])"' + go: 'func(text string) string { return text + "{{planet}} => |planet|" + text }' template: "{{= | | =}}<|#lambda|-|/lambda|>" expected: "<-{{planet}} => Earth->" @@ -158,6 +166,7 @@ tests: clojure: '(fn [text] (str "__" text "__"))' lisp: '(lambda (text) (format nil "__~a__" text))' pwsh: '"__$($args[0])__"' + go: 'func(text string) string { return "__" + text + "__" }' template: '{{#lambda}}FILE{{/lambda}} != {{#lambda}}LINE{{/lambda}}' expected: '__FILE__ != __LINE__' @@ -175,5 +184,6 @@ tests: clojure: '(fn [text] false)' lisp: '(lambda (text) (declare (ignore text)) nil)' pwsh: '$false' + go: 'func(text string) bool { return false }' template: "<{{^lambda}}{{static}}{{/lambda}}>" expected: "<>"