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

Shorthand syntax for filter tag #257

Open
wants to merge 2 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
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ _None_

### Enhancements

_None_
- Allow shorthand syntax for filter tags, i.e. `{% uppercase %}String{% enduppercase %}`.
[Ilya Puchka](https://github.com/ilyapuchka)
[#257](https://github.com/stencilproject/Stencil/pull/257)

### Deprecations

Expand Down
2 changes: 1 addition & 1 deletion Sources/Extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ class DefaultExtension: Extension {
registerTag("include", parser: IncludeNode.parse)
registerTag("extends", parser: ExtendsNode.parse)
registerTag("block", parser: BlockNode.parse)
registerTag("filter", parser: FilterNode.parse)
registerTag("filter", parser: FilterNode.parse(tag: "filter"))
}

fileprivate func registerDefaultFilters() {
Expand Down
30 changes: 16 additions & 14 deletions Sources/FilterTag.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,23 @@ class FilterNode : NodeType {
let nodes: [NodeType]
let token: Token?

class func parse(_ parser: TokenParser, token: Token) throws -> NodeType {
let bits = token.components

guard bits.count == 2 else {
throw TemplateSyntaxError("'filter' tag takes one argument, the filter expression")
class func parse(tag: String) -> Extension.TagParser {
return { parser, token in
let bits = token.components

guard bits.count <= 2 else {
throw TemplateSyntaxError("'filter' tag takes one argument, the filter expression")
}

let blocks = try parser.parse(until(["end\(tag)"]))

guard parser.nextToken() != nil else {
throw TemplateSyntaxError("`end\(tag)` was not found.")
}

let resolvable = try parser.compileFilter("filter_value|\(bits[bits.count - 1])", containedIn: token)
return FilterNode(nodes: blocks, resolvable: resolvable, token: token)
}

let blocks = try parser.parse(until(["endfilter"]))

guard parser.nextToken() != nil else {
throw TemplateSyntaxError("`endfilter` was not found.")
}

let resolvable = try parser.compileFilter("filter_value|\(bits[1])", containedIn: token)
return FilterNode(nodes: blocks, resolvable: resolvable, token: token)
}

init(nodes: [NodeType], resolvable: Resolvable, token: Token) {
Expand Down
9 changes: 7 additions & 2 deletions Sources/Parser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,13 @@ public class TokenParser {
return filter
}
}

throw TemplateSyntaxError("Unknown template tag '\(name)'")

let (name, _) = parseFilterComponents(token: name)
if environment.extensions.contains(where: { $0.filters[name] != nil }) {
return FilterNode.parse(tag: name)
} else {
throw TemplateSyntaxError("Unknown template tag '\(name)'")
}
}

func findFilter(_ name: String) throws -> FilterType {
Expand Down
18 changes: 18 additions & 0 deletions Tests/StencilTests/FilterTagSpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,24 @@ class FilterTagTests: XCTestCase {
""", context: ["items": ["\"1\"", "\"2\""]])
try expect(result) == "1,2"
}

$0.it("can render filter with shorthand syntax") {
let template = Template(templateString: "{% uppercase %}Test{% enduppercase %}")
let result = try template.render()
try expect(result) == "TEST"
}

$0.it("can render multiple filters with shorthand syntax") {
let ext = Extension()
ext.registerFilter("split", filter: {
return ($0 as! String).components(separatedBy: $1[0] as! String)
})
let env = Environment(extensions: [ext])
let result = try env.renderTemplate(string: """
{% split:","|join:";" %}{{ items|join:"," }}{% endsplit %}
""", context: ["items": [1, 2]])
try expect(result) == "1;2"
}
}
}
}
9 changes: 9 additions & 0 deletions docs/builtins.rst
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,15 @@ You can chain multiple filters with a pipe (`|`).
Capitalised.
{% endfilter %}

You can use shorthand syntax by dropping `filter` keyword and changing closing tag:

.. code-block:: html+django

{% lowercase %}
This Text Will First Be Lowercased, Then The First Character Will BE
Capitalised.
{% endlowercase %}

``include``
~~~~~~~~~~~

Expand Down