stencilproject / Stencil

Stencil is a simple and powerful template language for Swift.
https://stencil.fuller.li
BSD 2-Clause "Simplified" License
2.34k stars 223 forks source link

Expression support #117

Open svanimpe opened 7 years ago

svanimpe commented 7 years ago

Are there any plans to support simple expressions like {{ variable + 1 }} ?

When rendering a template, I set a page variable and wanted to use expressions like this to generate links to the previous and next pages. I created previous and next filters to work around this limitation.

kylef commented 7 years ago

I haven't planned to add expressions, expression support would encourage placing programming logic your templates. Stencils design goals are meant to express presentation and not programming logic.

In your case, wouldn't that type of logic need to know if there is a next and previous page instead of blindly assuming you can + or - 1 to find a closest sibling page? If so, I think it would make more sense to create some kind of "paginator" which handles all the logic so that a template can just deal with presentation of pagination instead of the underlying logic behind pagination.

For example:

protocol Paginator {
  var hasPrevious: Bool { get }
  var hasNext: Bool { get }

  var nextURL: String? { get }
  var previousURL: String? { get }

  var currentPageIndex: Int { get }
  var totalPages: Int { get }
}
{% if paginator.hasPrevious %}
  <a href="{{ paginator.previousURL }}">Previous Posts</a>
{% endif %}

Current page {{ paginator.currentPageIndex }} out of {{ paginator.totalPages }}.

{% if paginator.hasNext %}
    <a href="{{ paginator. nextURL }}">More Posts</a>
{% endif %}
svanimpe commented 7 years ago

@kylef I was using currentPage and hasNextPage as simple pagination info. That was the minimum information I needed. The web front-end already knows the URL of the endpoint, so pagination was as simple as currentPage - 1 if currentPage > 0 and currentPage + 1 if hasNextPage. But you're right, that wasn't very clean design :)

I was mostly wondering if you've come across other use cases that might need expression support (or similar extra features)?

shad0w-jo4n commented 5 years ago

@svanimpe For example, I needed even elements of the array to be displayed definitely, and odd elements in a different way, but the order of the output elements was the same as in the array. And using a class or structure to store the parity/odd of an element I don't think is rational.