Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Render tag #24

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Defines a default set of lint rules enforced for
# projects at Google. For details and rationale,
# see https://github.com/dart-lang/pedantic#enabled-lints.
include: package:pedantic/analysis_options.yaml

# see https://github.com/dart-lang/lints.
include: package:lints/core.yaml

# For lint rules and documentation, see http://dart-lang.github.io/linter/lints.
# Uncomment to specify additional rules.
Expand Down
113 changes: 113 additions & 0 deletions lib/src/buildin_tags/render.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import '../block.dart';
import '../context.dart';
import '../document.dart';
import '../expressions.dart';
import '../model.dart';
import '../parser/parser.dart';
import '../parser/tag_parser.dart';
import '../tag.dart';
import './for.dart';

class Render extends Block {
final List<_Assign> assignments;
final DocumentFuture childBuilder;
bool isLoop;

Render._(this.assignments, this.childBuilder, [this.isLoop = false]) : super([]);

@override
Stream<String> render(RenderContext context) async* {
var innerContext = context.cloneAsRoot();
innerContext.variables.clear();

if (isLoop) {
var collection = (assignments[0].from as LookupExpression).name.value;
var collectionValue = context.variables[collection];

innerContext.variables.addAll({collection: collectionValue});

For forBlock = For(assignments[0].to, assignments[0].from, [
await childBuilder.resolve(innerContext),
], []);
yield* forBlock.render(innerContext);
} else {
innerContext = innerContext.push({for (var a in assignments) a.to: await a.from.evaluate(context)});
yield* (await childBuilder.resolve(innerContext)).render(innerContext);
}
}

static BlockParserFactory factory = () => _RenderBlockParser();
}

class _Assign {
final String to;
final Expression from;

_Assign(this.to, this.from);
}

class _RenderBlockParser extends BlockParser {
@override
bool get hasEndTag => false;

@override
Block create(List<Token> tokens, List<Tag> children) {
bool hasFor = false;
final parser = TagParser.from(tokens);
final childBuilder = parser.parseDocumentReference(context);

var assignments = <_Assign>[];

if (parser.current.value == ",") {
parser.moveNext();

while (parser.current.type == TokenType.identifier) {
final to = parser.current;

if (parser.peekNext() != null && parser.peekNext()!.value == ",") {
assignments.add(_Assign(to.value, parser.parseSingleTokenExpression()));
parser.moveNext();
continue;
}

if (parser.current.value == ",") {
parser.moveNext();
}

if (parser.peekNext() != null) {
if (parser.peekNext()!.value == ":") {
parser.moveNext();
parser.moveNext();
parser.expect(types: [TokenType.identifier, TokenType.single_string, TokenType.double_string, TokenType.number]);
assignments.add(_Assign(to.value, parser.parseSingleTokenExpression()));
}
}
parser.moveNext();
}
}

if (['with', 'for'].contains(parser.current.value)) {
hasFor = parser.current.value == "for";

while (parser.current.type == TokenType.identifier) {
parser.expect(types: [TokenType.identifier]);

if (parser.peekNext() != null) {
parser.moveNext();
final to = parser.parseSingleTokenExpression();
if (parser.current.value == 'as') {
parser.moveNext();
parser.expect(types: [TokenType.identifier]);
assignments.add(_Assign(parser.current.value, to));
}
}
parser.moveNext();
}
}

return Render._(assignments, childBuilder, hasFor);
}

@override
void unexpectedTag(Parser parser, Token start, List<Token> args, List<Tag> childrenSoFar) {}
}
2 changes: 2 additions & 0 deletions lib/src/builtins.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import 'buildin_tags/for.dart';
import 'buildin_tags/if.dart';
import 'buildin_tags/ifchanged.dart';
import 'buildin_tags/include.dart';
import 'buildin_tags/render.dart';
import 'buildin_tags/load.dart';
import 'buildin_tags/named_block.dart';
import 'buildin_tags/regroup.dart';
Expand All @@ -27,6 +28,7 @@ class BuiltinsModule implements Module {
context.tags['if'] = If.factory;
context.tags['unless'] = If.unlessFactory;
context.tags['include'] = Include.factory;
context.tags['render'] = Render.factory;
context.tags['filter'] = BlockParser.simple(FilterBlock.factory);
context.tags['load'] = BlockParser.simple(Load.factory, hasEndTag: false);
context.tags['block'] = BlockParser.simple(NamedBlock.factory);
Expand Down
15 changes: 10 additions & 5 deletions lib/src/parser/parser.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import '../exception/parse_block_exception.dart';

import '../block.dart';
import '../context.dart';
import '../document.dart';
import '../errors.dart';
import '../exception/parse_block_exception.dart';
import '../expressions.dart';
import '../model.dart';
import '../tag.dart';
Expand Down Expand Up @@ -65,9 +64,15 @@ class Parser {
}

Token? asTarget;
if (args.length >= 2 && args[args.length - 1].type == TokenType.identifier && args[args.length - 2].value == 'as') {
asTarget = args.last;
args.length = args.length - 2;
if (args.where((element) => element.value == 'as').isNotEmpty) {
if (args.where((element) => ["with", "for"].contains(element.value)).isEmpty) {
if (args.length > 2 && args[args.length - 1].type == TokenType.identifier) {
if (args[args.length - 2].value == 'as') {
asTarget = args.last;
args.length = args.length - 2;
}
}
}
}

if (context.tags.containsKey(start.value)) {
Expand Down
30 changes: 21 additions & 9 deletions lib/src/parser/tag_parser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,28 @@ import '../model.dart';
class TagParser {
final Iterator<Token> tokens;

TagParser.from(List<Token> tokens) : this.fromIterator(tokens.followedBy([Token.eof]).iterator..moveNext());
int index = 0;

TagParser.fromIterator(this.tokens);
List<Token> _originalTokens = [];

TagParser.from(List<Token> tokens) : this.fromIterator(tokens.followedBy([Token.eof]).iterator..moveNext(), tokens);

TagParser.fromIterator(this.tokens, [this._originalTokens = const []]);

Token get current => tokens.current;

Token? peekNext() {
if (index >= _originalTokens.length) {
return null;
}
return _originalTokens.elementAt(index + 1);
}

bool moveNext() {
if (current == Token.eof) {
return true;
}
index += 1;
return tokens.moveNext();
}

Expand Down Expand Up @@ -98,7 +110,7 @@ class TagParser {
Expression parseSingleTokenExpression() {
expect(types: [TokenType.identifier, TokenType.single_string, TokenType.double_string, TokenType.number]);
final name = tokens.current;
tokens.moveNext();
moveNext();

if (name.type == TokenType.identifier) {
if (name.value == 'true') {
Expand All @@ -123,10 +135,10 @@ class TagParser {
var exp = parseSingleTokenExpression();

while (tokens.current.type == TokenType.dot) {
tokens.moveNext();
moveNext();

exp = MemberExpression(exp, tokens.current);
tokens.moveNext();
moveNext();
}

return exp;
Expand All @@ -143,17 +155,17 @@ class TagParser {

Expression parseFilters(Expression exp) {
while (tokens.current.type == TokenType.pipe) {
tokens.moveNext();
moveNext();

expect(types: [TokenType.identifier]);
final name = tokens.current;
final arguments = <Expression>[];

if (tokens.moveNext() && tokens.current.type == TokenType.colon) {
tokens.moveNext();
if (moveNext() && tokens.current.type == TokenType.colon) {
moveNext();
do {
arguments.add(parseMemberExpression());
} while (tokens.current.type == TokenType.comma && tokens.moveNext());
} while (tokens.current.type == TokenType.comma && moveNext());
}

exp = FilterExpression(exp, name, arguments);
Expand Down
5 changes: 3 additions & 2 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ version: 0.2.2
homepage: https://github.com/ergonlabs/liquid_dart

environment:
sdk: '>=2.12.0 <3.0.0'
sdk: '>=3.0.0 <=3.2.0'

dependencies:
string_scanner: ^1.1.0
more: 4.1.0

dev_dependencies:
pedantic: ^1.11.0
lints: ^3.0.0
test: ^1.17.7
33 changes: 29 additions & 4 deletions test/liquid_test.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import 'package:liquid_engine/liquid_engine.dart';
import 'package:liquid_engine/src/context.dart';
import 'package:liquid_engine/src/errors.dart';
import 'package:liquid_engine/src/exception/parse_block_exception.dart';
import 'package:liquid_engine/src/model.dart';
import 'package:liquid_engine/src/template.dart';
import 'package:test/test.dart';

void main() {
Expand Down Expand Up @@ -217,6 +213,35 @@ void main() {
expect(await template.render(context), equals('Hi, friend!'));
});

test('render', () async {
final context = Context.create();
final root = TestRoot({
'render': '{% render "name.html" %}',
'render_with_parameters': '{% render "name_age.html", first_name, last_name, age:1 %}',
'render_with_with': '{% render "name.html" with first_name as name %}',
'render_with_for': '{% render "name.html" for names as name %}',
'name_age.html': '{{ first_name }} {{ last_name }}! {{age}}',
'name.html': '{{ name }}!',
});

context.variables['first_name'] = 'John';
context.variables['last_name'] = 'John';
context.variables['greeting'] = 'Hello';
context.variables['names'] = ['john', 'mark', 'mary'];

var template = Template.parse(context, await root.resolve('render'));
expect(await template.render(context), equals('!'));

template = Template.parse(context, await root.resolve('render_with_parameters'));
expect(await template.render(context), equals('John John! 1'));

template = Template.parse(context, await root.resolve('render_with_with'));
expect(await template.render(context), equals('John!'));

template = Template.parse(context, await root.resolve('render_with_for'));
expect(await template.render(context), equals(['john', 'mark', 'mary'].map((e) => '$e!').join('')));
});

test('extends', () async {
final context = Context.create();
final root = TestRoot({
Expand Down