1
0
mirror of https://github.com/danog/liquid.git synced 2024-11-26 23:14:39 +01:00

Implement forloop variables

This commit is contained in:
Oliver Steele 2017-06-28 20:49:38 -04:00
parent 3a1506badf
commit e9c35a35d0
10 changed files with 487 additions and 45 deletions

View File

@ -26,7 +26,7 @@
- [x] modifiers (`limit`, `reversed`, `offset`)
- [ ] `range`
- [ ] `break`, `continue`
- [ ] loop variables
- [x] loop variables
- [ ] `tablerow`
- [ ] `cycle`
- [x] Raw

View File

@ -28,7 +28,12 @@ func (c Context) GetVariableMap() map[string]interface{} {
return c.vars
}
// Set sets a variable value within an evaluation context.
// Get gets a variable value within an evaluation context.
func (c Context) Get(name string) interface{} {
return c.vars[name]
}
// Set sets a variable value from an evaluation context.
func (c Context) Set(name string, value interface{}) {
c.vars[name] = value
}

View File

@ -23,15 +23,13 @@ func init() {
}
// Engine parses template source into renderable text.
//
// In the future, it will be configured with additional tags, filters, and the {%include%} search path.
type Engine interface {
DefineFilter(name string, fn interface{})
DefineTag(string, func(form string) (func(io.Writer, chunks.Context) error, error))
ParseTemplate(text []byte) (Template, error)
ParseAndRender(text []byte, scope map[string]interface{}) ([]byte, error)
ParseAndRenderString(text string, scope map[string]interface{}) (string, error)
ParseAndRender(text []byte, bindings map[string]interface{}) ([]byte, error)
ParseAndRenderString(text string, bindings map[string]interface{}) (string, error)
}
type TagDefinition func(expr string) (func(io.Writer, chunks.Context) error, error)
@ -42,16 +40,30 @@ type template struct {
ast chunks.ASTNode
}
// NewEngine makes a new engine.
// NewEngine returns a new engine.
func NewEngine() Engine {
return engine{}
}
// DefineFilter defines a Liquid filter.
//
// A filter is any function that takes at least one input, and returns one or two outputs.
// If it returns two outputs, the second must be an error.
//
// Note: Although this function is defined on the engine, its effect is currently global.
func (e engine) DefineFilter(name string, fn interface{}) {
// TODO define this on the engine, not globally
expressions.DefineFilter(name, fn)
}
// DefineTag defines a Liquid filter.
//
// A tag is any function that takes at least one input, and returns one or two outputs.
// If it returns two outputs, the second must be an error.
//
// Note: This interface is likely to change.
//
// Note: Although this function is defined on the engine, its effect is currently global.
func (e engine) DefineTag(name string, td func(form string) (func(io.Writer, chunks.Context) error, error)) {
// TODO define this on the engine, not globally
chunks.DefineTag(name, chunks.TagDefinition(td))
@ -60,7 +72,6 @@ func (e engine) DefineTag(name string, td func(form string) (func(io.Writer, chu
func (e engine) ParseTemplate(text []byte) (Template, error) {
tokens := chunks.Scan(string(text), "")
ast, err := chunks.Parse(tokens)
// fmt.Println(chunks.MustYAML(ast))
if err != nil {
return nil, err
}
@ -68,17 +79,17 @@ func (e engine) ParseTemplate(text []byte) (Template, error) {
}
// ParseAndRender parses and then renders the template.
func (e engine) ParseAndRender(text []byte, scope map[string]interface{}) ([]byte, error) {
func (e engine) ParseAndRender(text []byte, bindings map[string]interface{}) ([]byte, error) {
t, err := e.ParseTemplate(text)
if err != nil {
return nil, err
}
return t.Render(scope)
return t.Render(bindings)
}
// ParseAndRenderString is a convenience wrapper for ParseAndRender, that has string input and output.
func (e engine) ParseAndRenderString(text string, scope map[string]interface{}) (string, error) {
b, err := e.ParseAndRender([]byte(text), scope)
func (e engine) ParseAndRenderString(text string, bindings map[string]interface{}) (string, error) {
b, err := e.ParseAndRender([]byte(text), bindings)
if err != nil {
return "", err
}

View File

@ -16,7 +16,7 @@ func init() {
name string
val interface{}
f func(Context) interface{}
loopmods LoopModifiers
loopmods loopModifiers
filter_params []valueFn
}
%type <f> expr rel filtered cond loop
@ -49,7 +49,7 @@ loop: IDENTIFIER IN filtered loop_modifiers ';' {
}
;
loop_modifiers: /* empty */ { $$ = LoopModifiers{} }
loop_modifiers: /* empty */ { $$ = loopModifiers{} }
| loop_modifiers IDENTIFIER {
switch $2 {
case "reversed":

View File

@ -8,12 +8,12 @@ import (
// Loop describes the result of parsing and then evaluating a loop statement.
type Loop struct {
Name string
Expr interface{}
LoopModifiers
Variable string
Expr interface{}
loopModifiers
}
type LoopModifiers struct {
type loopModifiers struct {
Limit *int
Offset int
Reversed bool

View File

@ -21,7 +21,7 @@ type yySymType struct {
name string
val interface{}
f func(Context) interface{}
loopmods LoopModifiers
loopmods loopModifiers
filter_params []valueFn
}
@ -537,7 +537,7 @@ yydefault:
yyDollar = yyS[yypt-0 : yypt+1]
//line expressions.y:52
{
yyVAL.loopmods = LoopModifiers{}
yyVAL.loopmods = loopModifiers{}
}
case 6:
yyDollar = yyS[yypt-2 : yypt+1]

View File

@ -36,6 +36,17 @@ func loopTag(node chunks.ASTControlTag) func(io.Writer, chunks.Context) error {
if loop.Limit != nil {
limit = *loop.Limit
}
const forloopName = "forloop"
defer func(index, forloop interface{}) {
ctx.Set(forloopName, index)
ctx.Set(loop.Variable, forloop)
}(ctx.Get(forloopName), ctx.Get(loop.Variable))
// for forloop variable
var (
first = true
index = 1
length = limit
)
for i := start; i < rt.Len(); i++ {
if limit == 0 {
break
@ -45,13 +56,22 @@ func loopTag(node chunks.ASTControlTag) func(io.Writer, chunks.Context) error {
if loop.Reversed {
j = rt.Len() - 1 - i
}
ctx.Set(loop.Name, rt.Index(j).Interface())
ctx.Set(loop.Variable, rt.Index(j).Interface())
ctx.Set(forloopName, map[string]interface{}{
"first": first,
"last": limit == 0,
"index": index,
"index0": index - 1,
"rindex": length + 1 - index,
"rindex0": length - index,
"length": length,
})
first, index = false, index+1
err := ctx.RenderASTSequence(w, node.Body)
if err != nil {
return err
}
}
ctx.Set(loop.Name, nil)
return nil
}
}

View File

@ -18,28 +18,20 @@ var parseErrorTests = []struct{ in, expected string }{
}
var tagTests = []struct{ in, expected string }{
// variables
{`{%assign av = 1%}{{av}}`, "1"},
{`{%assign av = obj.a%}{{av}}`, "1"},
{`{%capture x%}captured{%endcapture%}{{x}}`, "captured"},
// TODO test whether this requires matching interior tags
{`{%comment%}{{a}}{%unknown%}{%endcomment%}`, ""},
{`{%capture x%}captured{%endcapture%}{{x}}`, "captured"},
// conditionals
{`{%case 1%}{%when 1%}a{%when 2%}b{%endcase%}`, "a"},
{`{%case 2%}{%when 1%}a{%when 2%}b{%endcase%}`, "b"},
{`{%case 3%}{%when 1%}a{%when 2%}b{%endcase%}`, ""},
// {`{%case 2%}{%when 1%}a{%else 2%}b{%endcase%}`, "captured"},
{`{%for a in ar%}{{a}} {%endfor%}`, "first second third "},
{`{%for a in ar reversed%}{{a}} {%endfor%}`, "third second first "},
{`{%for a in ar limit:2%}{{a}} {%endfor%}`, "first second "},
{`{%for a in ar offset:1%}{{a}} {%endfor%}`, "second third "},
{`{%for a in ar reversed offset:1%}{{a}} {%endfor%}`, "second first "},
{`{%for a in ar reversed limit:1%}{{a}} {%endfor%}`, "third "},
{`{%for a in ar limit:1 offset:1%}{{a}} {%endfor%}`, "second "},
{`{%for a in ar reversed limit:1 offset:1%}{{a}} {%endfor%}`, "second "},
{`{%if true%}true{%endif%}`, "true"},
{`{%if false%}false{%endif%}`, ""},
{`{%if 0%}true{%endif%}`, "true"},
@ -54,10 +46,6 @@ var tagTests = []struct{ in, expected string }{
{`{%if false%}0{%elsif true%}1{%else%}2{%endif%}`, "1"},
{`{%if false%}0{%elsif false%}1{%else%}2{%endif%}`, "2"},
// TODO test whether this requires matching interior tags
{`pre{%raw%}{{a}}{%unknown%}{%endraw%}post`, "pre{{a}}{%unknown%}post"},
{`pre{%raw%}{%if false%}anyway-{%endraw%}post`, "pre{%if false%}anyway-post"},
{`{%unless true%}false{%endunless%}`, ""},
{`{%unless false%}true{%endunless%}`, "true"},
{`{%unless true%}false{%else%}true{%endunless%}`, "true"},
@ -65,6 +53,39 @@ var tagTests = []struct{ in, expected string }{
{`{%unless false%}0{%elsif true%}1{%else%}2{%endunless%}`, "0"},
{`{%unless true%}0{%elsif true%}1{%else%}2{%endunless%}`, "1"},
{`{%unless true%}0{%elsif false%}1{%else%}2{%endunless%}`, "2"},
// loops
{`{%for a in ar%}{{a}} {%endfor%}`, "first second third "},
// loop modifiers
{`{%for a in ar reversed%}{{a}} {%endfor%}`, "third second first "},
{`{%for a in ar limit:2%}{{a}} {%endfor%}`, "first second "},
{`{%for a in ar offset:1%}{{a}} {%endfor%}`, "second third "},
{`{%for a in ar reversed offset:1%}{{a}} {%endfor%}`, "second first "},
{`{%for a in ar reversed limit:1%}{{a}} {%endfor%}`, "third "},
{`{%for a in ar limit:1 offset:1%}{{a}} {%endfor%}`, "second "},
{`{%for a in ar reversed limit:1 offset:1%}{{a}} {%endfor%}`, "second "},
// loop variables
{`{%for a in ar%}{{forloop.index}}:{{forloop.first}} {%endfor%}`, "1:true 2: 3: "},
{`{%for a in ar%}{{forloop.index}}:{{forloop.last}} {%endfor%}`, "1: 2: 3:true "},
{`{%for a in ar%}{{forloop.index}} {%endfor%}`, "1 2 3 "},
{`{%for a in ar%}{{forloop.index0}} {%endfor%}`, "0 1 2 "},
{`{%for a in ar%}{{forloop.rindex}} {%endfor%}`, "3 2 1 "},
{`{%for a in ar%}{{forloop.rindex0}} {%endfor%}`, "2 1 0 "},
{`{%for a in ar%}{{forloop.length}} {%endfor%}`, "3 3 3 "},
{`{%for i in ar%}{{forloop.index}}[{%for j in ar%}{{forloop.index}}{%endfor%}]{{forloop.index}} {%endfor%}`,
"1[123]1 2[123]2 3[123]3 "},
{`{%for a in ar reversed%}{{forloop.index}} {%endfor%}`, "1 2 3 "},
{`{%for a in ar reversed%}{{forloop.rindex}} {%endfor%}`, "3 2 1 "},
{`{%for a in ar reversed%}{{forloop.length}} {%endfor%}`, "3 3 3 "},
{`{%for a in ar limit:2%}{{forloop.index}} {%endfor%}`, "1 2 "},
{`{%for a in ar limit:2%}{{forloop.rindex}} {%endfor%}`, "2 1 "},
{`{%for a in ar limit:2%}{{forloop.length}} {%endfor%}`, "2 2 "},
// TODO test whether this requires matching interior tags
{`pre{%raw%}{{a}}{%unknown%}{%endraw%}post`, "pre{{a}}{%unknown%}post"},
{`pre{%raw%}{%if false%}anyway-{%endraw%}post`, "pre{%if false%}anyway-post"},
}
var tagTestContext = chunks.NewContext(map[string]interface{}{

View File

@ -8,16 +8,18 @@ import (
// Template renders a template according to scope.
//
// Scope is a map of liquid variable names to objects.
// Bindings is a map of liquid variable names to objects.
type Template interface {
Render(scope map[string]interface{}) ([]byte, error)
RenderString(scope map[string]interface{}) (string, error)
// Render executes the template with the specified bindings.
Render(bindings map[string]interface{}) ([]byte, error)
// RenderString is a convenience wrapper for Render, that has string input and output.
RenderString(bindings map[string]interface{}) (string, error)
}
// Render applies the template to the scope.
func (t *template) Render(scope map[string]interface{}) ([]byte, error) {
// Render executes the template within the bindings environment.
func (t *template) Render(bindings map[string]interface{}) ([]byte, error) {
buf := new(bytes.Buffer)
err := t.ast.Render(buf, chunks.NewContext(scope))
err := t.ast.Render(buf, chunks.NewContext(bindings))
if err != nil {
return nil, err
}
@ -25,8 +27,8 @@ func (t *template) Render(scope map[string]interface{}) ([]byte, error) {
}
// RenderString is a convenience wrapper for Render, that has string input and output.
func (t *template) RenderString(scope map[string]interface{}) (string, error) {
b, err := t.Render(scope)
func (t *template) RenderString(bindings map[string]interface{}) (string, error) {
b, err := t.Render(bindings)
if err != nil {
return "", err
}

383
test.html Normal file
View File

@ -0,0 +1,383 @@
<!--
Copyright 2009 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<!--
Note: Static (i.e., not template-generated) href and id
attributes start with "pkg-" to make it impossible for
them to conflict with generated attributes (some of which
correspond to Go identifiers).
-->
<script type='text/javascript'>
document.ANALYSIS_DATA = ;
document.CALLGRAPH = ;
</script>
<div id="short-nav">
<dl>
<dd><code>import "."</code></dd>
</dl>
<dl>
<dd><a href="#pkg-overview" class="overviewLink">Overview</a></dd>
<dd><a href="#pkg-index" class="indexLink">Index</a></dd>
<dd><a href="#pkg-examples" class="examplesLink">Examples</a></dd>
<dd><a href="#pkg-subdirectories">Subdirectories</a></dd>
</dl>
</div>
<!-- The package's Name is printed as title by the top-level template -->
<div id="pkg-overview" class="toggleVisible">
<div class="collapsed">
<h2 class="toggleButton" title="Click to show Overview section">Overview ▹</h2>
</div>
<div class="expanded">
<h2 class="toggleButton" title="Click to hide Overview section">Overview ▾</h2>
<p>
Package liquid is a pure Go implementation of Shopify Liquid templates.
</p>
<p>
It&#39;s intended for use in for use in <a href="https://github.com/osteele/gojekyll">https://github.com/osteele/gojekyll</a>.
</p>
<p>
See the project README <a href="https://github.com/osteele/liquid">https://github.com/osteele/liquid</a> for additional information and implementation status.
</p>
</div>
</div>
<div id="example_" class="toggle">
<div class="collapsed">
<p class="exampleHeading toggleButton"><span class="text">Example</span></p>
</div>
<div class="expanded">
<p class="exampleHeading toggleButton"><span class="text">Example</span></p>
<p>Code:</p>
<pre class="code">engine := NewEngine()
template := `&lt;h1&gt;{{page.title}}&lt;/h1&gt;`
scope := map[string]interface{}{
&#34;page&#34;: map[string]interface{}{
&#34;title&#34;: &#34;Introduction&#34;,
},
}
out, err := engine.ParseAndRenderString(template, scope)
if err != nil {
log.Fatalln(err)
}
fmt.Println(out)
<span class="comment"></pre>
<p>Output:</p>
<pre class="output">&lt;h1&gt;Introduction&lt;/h1&gt;
</pre>
</div>
</div>
<div id="pkg-index" class="toggleVisible">
<div class="collapsed">
<h2 class="toggleButton" title="Click to show Index section">Index ▹</h2>
</div>
<div class="expanded">
<h2 class="toggleButton" title="Click to hide Index section">Index ▾</h2>
<!-- Table of contents for API; must be named manual-nav to turn off auto nav. -->
<div id="manual-nav">
<dl>
<dd><a href="#Engine">type Engine</a></dd>
<dd>&nbsp; &nbsp; <a href="#NewEngine">func NewEngine() Engine</a></dd>
<dd><a href="#TagDefinition">type TagDefinition</a></dd>
<dd><a href="#Template">type Template</a></dd>
</dl>
</div><!-- #manual-nav -->
<div id="pkg-examples">
<h4>Examples</h4>
<dl>
<dd><a class="exampleLink" href="#example_">Package</a></dd>
</dl>
</div>
<h4>Package files</h4>
<p>
<span style="font-size:90%">
<a href="/src/target/engine.go">engine.go</a>
<a href="/src/target/template.go">template.go</a>
</span>
</p>
</div><!-- .expanded -->
</div><!-- #pkg-index -->
<div id="pkg-callgraph" class="toggle" style="display: none">
<div class="collapsed">
<h2 class="toggleButton" title="Click to show Internal Call Graph section">Internal call graph ▹</h2>
</div> <!-- .expanded -->
<div class="expanded">
<h2 class="toggleButton" title="Click to hide Internal Call Graph section">Internal call graph ▾</h2>
<p>
In the call graph viewer below, each node
is a function belonging to this package
and its children are the functions it
calls&mdash;perhaps dynamically.
</p>
<p>
The root nodes are the entry points of the
package: functions that may be called from
outside the package.
There may be non-exported or anonymous
functions among them if they are called
dynamically from another package.
</p>
<p>
Click a node to visit that function's source code.
From there you can visit its callers by
clicking its declaring <code>func</code>
token.
</p>
<p>
Functions may be omitted if they were
determined to be unreachable in the
particular programs or tests that were
analyzed.
</p>
<!-- Zero means show all package entry points. -->
<ul style="margin-left: 0.5in" id="callgraph-0" class="treeview"></ul>
</div>
</div> <!-- #pkg-callgraph -->
<h2 id="Engine">type <a href="/src/target/engine.go?s=640:1002#L16">Engine</a>
<a class="permalink" href="#Engine">&#xb6;</a>
</h2>
<p>
Engine parses template source into renderable text.
</p>
<pre>type Engine interface {
DefineFilter(name <a href="/pkg/builtin/#string">string</a>, fn interface{})
DefineTag(<a href="/pkg/builtin/#string">string</a>, func(form <a href="/pkg/builtin/#string">string</a>) (func(<a href="/pkg/io/">io</a>.<a href="/pkg/io/#Writer">Writer</a>, <a href="/pkg/github.com/osteele/liquid/chunks/">chunks</a>.<a href="/pkg/github.com/osteele/liquid/chunks/#Context">Context</a>) <a href="/pkg/builtin/#error">error</a>, <a href="/pkg/builtin/#error">error</a>))
ParseTemplate(text []<a href="/pkg/builtin/#byte">byte</a>) (<a href="#Template">Template</a>, <a href="/pkg/builtin/#error">error</a>)
ParseAndRender(text []<a href="/pkg/builtin/#byte">byte</a>, bindings map[<a href="/pkg/builtin/#string">string</a>]interface{}) ([]<a href="/pkg/builtin/#byte">byte</a>, <a href="/pkg/builtin/#error">error</a>)
ParseAndRenderString(text <a href="/pkg/builtin/#string">string</a>, bindings map[<a href="/pkg/builtin/#string">string</a>]interface{}) (<a href="/pkg/builtin/#string">string</a>, <a href="/pkg/builtin/#error">error</a>)
}</pre>
<h3 id="NewEngine">func <a href="/src/target/engine.go?s=1192:1215#L34">NewEngine</a>
<a class="permalink" href="#NewEngine">&#xb6;</a>
</h3>
<pre>func NewEngine() <a href="#Engine">Engine</a></pre>
<p>
NewEngine returns a new engine.
</p>
<h2 id="TagDefinition">type <a href="/src/target/engine.go?s=1004:1087#L25">TagDefinition</a>
<a class="permalink" href="#TagDefinition">&#xb6;</a>
</h2>
<pre>type TagDefinition func(expr <a href="/pkg/builtin/#string">string</a>) (func(<a href="/pkg/io/">io</a>.<a href="/pkg/io/#Writer">Writer</a>, <a href="/pkg/github.com/osteele/liquid/chunks/">chunks</a>.<a href="/pkg/github.com/osteele/liquid/chunks/#Context">Context</a>) <a href="/pkg/builtin/#error">error</a>, <a href="/pkg/builtin/#error">error</a>)</pre>
<h2 id="Template">type <a href="/src/target/template.go?s=186:483#L2">Template</a>
<a class="permalink" href="#Template">&#xb6;</a>
</h2>
<p>
Template renders a template according to scope.
</p>
<p>
Bindings is a map of liquid variable names to objects.
</p>
<pre>type Template interface {
<span class="comment">// Render executes the template with the specified bindings.</span>
Render(bindings map[<a href="/pkg/builtin/#string">string</a>]interface{}) ([]<a href="/pkg/builtin/#byte">byte</a>, <a href="/pkg/builtin/#error">error</a>)
<span class="comment">// RenderString is a convenience wrapper for Render, that has string input and output.</span>
RenderString(bindings map[<a href="/pkg/builtin/#string">string</a>]interface{}) (<a href="/pkg/builtin/#string">string</a>, <a href="/pkg/builtin/#error">error</a>)
}</pre>
<h2 id="pkg-subdirectories">Subdirectories</h2>
<div class="pkg-dir">
<table>
<tr>
<th class="pkg-name">Name</th>
<th class="pkg-synopsis">Synopsis</th>
</tr>
<tr>
<td colspan="2"><a href="..">..</a></td>
</tr>
<tr>
<td class="pkg-name" style="padding-left: 0px;">
<a href="chunks/">chunks</a>
</td>
<td class="pkg-synopsis">
</td>
</tr>
<tr>
<td class="pkg-name" style="padding-left: 0px;">
<a href="errors/">errors</a>
</td>
<td class="pkg-synopsis">
</td>
</tr>
<tr>
<td class="pkg-name" style="padding-left: 0px;">
<a href="expressions/">expressions</a>
</td>
<td class="pkg-synopsis">
</td>
</tr>
<tr>
<td class="pkg-name" style="padding-left: 0px;">
<a href="filters/">filters</a>
</td>
<td class="pkg-synopsis">
</td>
</tr>
<tr>
<td class="pkg-name" style="padding-left: 0px;">
<a href="generics/">generics</a>
</td>
<td class="pkg-synopsis">
</td>
</tr>
<tr>
<td class="pkg-name" style="padding-left: 0px;">
<a href="tags/">tags</a>
</td>
<td class="pkg-synopsis">
</td>
</tr>
</table>
</div>