Skip to content

Commit

Permalink
v4: raw block helpers fixes #444
Browse files Browse the repository at this point in the history
  • Loading branch information
jknack committed Nov 9, 2015
1 parent 749f867 commit 9fcbf00
Show file tree
Hide file tree
Showing 7 changed files with 159 additions and 40 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -159,12 +159,23 @@ COMMENT
;

START_AMP
: {startToken(start, "&")}? . -> pushMode(VAR)
:
{startToken(start, "&")}? . -> pushMode(VAR)
;

END_RAW_BLOCK
: {startToken(start, "{{/")}? . -> pushMode(VAR)
;

START_RAW
:
{startToken(start, "{{")}? . -> pushMode(VAR)
;

START_T
: {startToken(start, "{")}? . -> pushMode(VAR)
;
:
{startToken(start, "{")}? . -> pushMode(VAR)
;

UNLESS
: {startToken(start, "^")}? . -> pushMode(VAR)
Expand Down Expand Up @@ -208,24 +219,48 @@ NL
mode SET_DELIMS;

END_DELIM
: {endToken("=" + end)}? . -> popMode
:
{endToken("=" + end)}? . -> popMode
;

WS_DELIM
: [ \t\r\n]
:
[ \t\r\n]
;

DELIM: .;
DELIM
:
.
;

mode RAW;

RAW_SPACE
:
[ \t\r\n]
;

RAW_CONTENT
:
{consumeUntil(start + "{{/")}? . -> popMode
;

mode VAR;

END_RAW
:
{endToken(end, "}}")}? . -> mode(RAW)
;

END_T
: {endToken(end, "}")}? . -> popMode
;
:
{endToken(end, "}")}? . -> popMode
;

END
: {endToken(end)}? . -> mode(DEFAULT_MODE)
;
:
{endToken(end)}? . -> mode(DEFAULT_MODE)
;

DECORATOR
:
Expand All @@ -243,17 +278,18 @@ PIPE
;

DOUBLE_STRING
:
'"' ( '\\"' | ~[\n] )*? '"'
;
:
'"' ( '\\"' | ~[\n] )*? '"'
;

SINGLE_STRING
:
'\'' ( '\\\'' | ~[\n] )*? '\''
;
:
'\'' ( '\\\'' | ~[\n] )*? '\''
;

EQ
: '='
:
'='
;

INT
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ statement
| unless
| partial
| partialBlock
| rawBlock
| escape
| comment
| delimiters
Expand All @@ -67,7 +68,10 @@ escape
;

text
: TEXT
:
TEXT
| RAW_CONTENT
| RAW_SPACE
;

spaces
Expand All @@ -86,6 +90,13 @@ block
END_BLOCK nameEnd=QID END
;

rawBlock
:
startToken = START_RAW sexpr END_RAW
thenBody=body
END_RAW_BLOCK nameEnd=QID END_RAW
;

blockParams
:
AS PIPE QID+ PIPE
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,17 +111,18 @@ class Block extends HelperResolver {
* @param handlebars The handlebars object.
* @param name The section's name.
* @param inverted True if it's inverted.
* @param type Block type: <code>#</code>, <code>^</code>, <code>#*</code>, <code>{{</code>.
* @param params The parameter list.
* @param hash The hash.
* @param blockParams The block param names.
*/
public Block(final Handlebars handlebars, final String name,
final boolean inverted, final List<Object> params,
final boolean inverted, final String type, final List<Object> params,
final Map<String, Object> hash, final List<String> blockParams) {
super(handlebars);
this.name = notNull(name, "The name is required.");
this.inverted = inverted;
type = inverted ? "^" : "#";
this.type = type;
params(params);
hash(hash);
this.blockParams = blockParams;
Expand Down Expand Up @@ -311,7 +312,7 @@ public String text() {
*/
private String text(final boolean complete) {
StringBuilder buffer = new StringBuilder();
buffer.append(startDelimiter).append(type).append(suffix()).append(name);
buffer.append(startDelimiter).append(type).append(name);
String params = paramsToString(this.params);
if (params.length() > 0) {
buffer.append(" ").append(params);
Expand All @@ -330,17 +331,14 @@ private String text(final boolean complete) {
} else {
buffer.append("\n...\n");
}
buffer.append(startDelimiter).append('/').append(name).append(endDelimiter);
buffer.append(startDelimiter);
if (type.equals("{{")) {
buffer.append("{{");
}
buffer.append('/').append(name).append(endDelimiter);
return buffer.toString();
}

/**
* @return Block suffix, default is empty.
*/
protected String suffix() {
return "";
}

/**
* The start delimiter.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public class BlockDecorator extends Block {
public BlockDecorator(final Handlebars handlebars, final String name, final boolean inverted,
final List<Object> params, final Map<String, Object> hash, final List<String> blockParams,
final boolean root) {
super(handlebars, name, inverted, params, hash, blockParams);
super(handlebars, name, inverted, "#*", params, hash, blockParams);
this.root = root;
this.tagType = TagType.START_SECTION;
}
Expand Down Expand Up @@ -87,11 +87,6 @@ public void before(final Context context, final Writer writer) throws IOExceptio
decorator.apply(body, options);
}

@Override
protected String suffix() {
return "*";
}

@Override
public void apply(final Context context, final Writer writer) throws IOException {
// NOOP
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
import com.github.jknack.handlebars.internal.HbsParser.ParamContext;
import com.github.jknack.handlebars.internal.HbsParser.PartialBlockContext;
import com.github.jknack.handlebars.internal.HbsParser.PartialContext;
import com.github.jknack.handlebars.internal.HbsParser.RawBlockContext;
import com.github.jknack.handlebars.internal.HbsParser.RefParamContext;
import com.github.jknack.handlebars.internal.HbsParser.SexprContext;
import com.github.jknack.handlebars.internal.HbsParser.SpacesContext;
Expand Down Expand Up @@ -150,6 +151,39 @@ public Template visit(final ParseTree tree) {
return (Template) super.visit(tree);
}

@Override
public Template visitRawBlock(final RawBlockContext ctx) {
level += 1;
SexprContext sexpr = ctx.sexpr();
Token nameStart = sexpr.QID().getSymbol();
String name = nameStart.getText();
qualifier.addLast(name);
String nameEnd = ctx.nameEnd.getText();
if (!name.equals(nameEnd)) {
reportError(null, ctx.nameEnd.getLine(), ctx.nameEnd.getCharPositionInLine(),
String.format("found: '%s', expected: '%s'", nameEnd, name));
}

hasTag(true);
Block block = new Block(handlebars, name, false, "{{", params(sexpr.param()),
hash(sexpr.hash()), Collections.<String> emptyList());
block.filename(source.filename());
block.position(nameStart.getLine(), nameStart.getCharPositionInLine());
String startDelim = ctx.start.getText();
startDelim = startDelim.substring(0, startDelim.length() - 2);
block.startDelimiter(startDelim);
block.endDelimiter(ctx.stop.getText());

Template body = visitBody(ctx.thenBody);
if (body != null) {
block.body(body);
}
hasTag(true);
qualifier.removeLast();
level -= 1;
return block;
}

@Override
public Template visitBlock(final BlockContext ctx) {
level += 1;
Expand All @@ -170,7 +204,7 @@ public Template visitBlock(final BlockContext ctx) {
block = new BlockDecorator(handlebars, name, false, params(sexpr.param()),
hash(sexpr.hash()), blockParams(ctx.blockParams()), level == 1);
} else {
block = new Block(handlebars, name, false, params(sexpr.param()),
block = new Block(handlebars, name, false, "#", params(sexpr.param()),
hash(sexpr.hash()), blockParams(ctx.blockParams()));
}
block.filename(source.filename());
Expand Down Expand Up @@ -204,7 +238,7 @@ public Template visitBlock(final BlockContext ctx) {
SexprContext elseexpr = elseStmtChain.sexpr();
Token elsenameStart = elseexpr.QID().getSymbol();
String elsename = elsenameStart.getText();
Block elseblock = new Block(handlebars, elsename, false, params(elseexpr.param()),
Block elseblock = new Block(handlebars, elsename, false, "#", params(elseexpr.param()),
hash(elseexpr.hash()), blockParams(elseStmtChain.blockParams()));
elseblock.filename(source.filename());
elseblock.position(elsenameStart.getLine(), elsenameStart.getCharPositionInLine());
Expand Down Expand Up @@ -240,7 +274,7 @@ public Template visitUnless(final UnlessContext ctx) {
reportError(null, ctx.nameEnd.getLine(), ctx.nameEnd.getCharPositionInLine(),
String.format("found: '%s', expected: '%s'", nameEnd, name));
}
Block block = new Block(handlebars, name, true, Collections.emptyList(),
Block block = new Block(handlebars, name, true, "^", Collections.emptyList(),
Collections.<String, Object> emptyMap(), blockParams(ctx.blockParams()));
block.filename(source.filename());
block.position(nameStart.getLine(), nameStart.getCharPositionInLine());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.github.jknack.handlebars;

import static org.junit.Assert.assertEquals;

import java.io.IOException;

import org.junit.Test;

public class RawHelperTest extends AbstractTest {

@Test
public void helperForRawBlockGetsRawContent() throws IOException {
shouldCompileTo("{{{{raw}}}} {{test}} {{{{/raw}}}}", $, $("raw", new Helper<Object>() {

@Override
public CharSequence apply(final Object context, final Options options) throws IOException {
return options.fn();
}

}), " {{test}} ");
}

@Test
public void text() throws IOException {
assertEquals("{{{{raw}}}} {{test}} {{{{/raw}}}}", compile("{{{{raw}}}} {{test}} {{{{/raw}}}}").text());
}

@Test
public void helperForRawBlockGetsParameters() throws IOException {
shouldCompileTo("{{{{raw 1 2 3}}}} {{test}} {{{{/raw}}}}", $, $("raw", new Helper<Object>() {

@Override
public CharSequence apply(final Object context, final Options options) throws IOException {
return options.fn().toString() + context + options.param(0) + options.param(1);
}

}), " {{test}} 123");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,18 @@

public class HbsParserTest {

private boolean printTokens = false;
private boolean printTokens = true;

@Test
public void hello() {
parse("Hello {{who}}\n!");
}

@Test
public void rawblock() {
parse("{{{{raw}}}} {{test}} {{{{/raw}}}}");
}

@Test
public void dynamicPartial() {
parse("{{> (partial)}}");
Expand Down Expand Up @@ -133,6 +138,7 @@ void setEnd(final String end) {
};
parser.removeErrorListeners();
parser.addErrorListener(errorReporter);
ParseTree tree = parser.template();
if (printTokens) {
String[] tokenNames = parser.tokenNames();
for (Token token : tokens.getTokens()) {
Expand All @@ -142,7 +148,6 @@ void setEnd(final String end) {
System.out.println(message);
}
}
ParseTree tree = parser.template();
System.out.println(tree.toStringTree(parser));
return tree;
}
Expand Down

0 comments on commit 9fcbf00

Please sign in to comment.