lambdas documentation

This commit is contained in:
Daniel Sipka 2015-04-24 15:51:41 +02:00
parent a8afdcef90
commit 25b002bacb

View File

@ -43,7 +43,7 @@ int main() {
The output of this example will be:
```
```html
Hi Chris!
Hi Mark!
Hi Scott!
@ -66,7 +66,7 @@ a JSON object.
Note that when using a `std::string` as value you must explicitly specify the
type, since a `const char*` literal like `"foobar"` would be implicitly
converted to bool. Alternatively you can use [C++14 string_literals](http://en.cppreference.com/w/cpp/string/basic_string/operator%22%22s)
converted to `bool`. Alternatively you can use [C++14 string_literals](http://en.cppreference.com/w/cpp/string/basic_string/operator%22%22s)
if your compiler supports it.
## Advanced usage
@ -92,7 +92,7 @@ std::cout << mstch::render(view, context, {{"user", user_view}}) << std::endl;
The output will be:
```
```html
<strong>Chris</strong>
<strong>Mark</strong>
<strong>Scott</strong>
@ -100,7 +100,51 @@ The output will be:
### Lambdas
TODO
C++11 lambda expressions can be used to add logic to your templates. Like a
`const char*` literal, lambdas can be implicitly converted to `bool`, so they
must be wrapped in a `mstch::lambda` object when used in a `mstch::node`.
The lambda expression passed to `mstch::lambda` returns a `std::string` and
accepts either no parameters:
```c++
std::string view{"Hello {{lambda}}!"};
mstch::map context{
{"lambda", mstch::lambda{[]() {
return std::string{"World"};
}}}
};
std::cout << mstch::render(view, context) << std::endl;
```
The output will be:
```html
Hello World!
```
Or it accepts a `const std::string&` and a `mstch::renderer`. The first one is
passed the unrendered literal block, the second is a `std::function` that can be
called to render it:
```c++
std::string view{"{{#bold}}{{yay}} :){{/bold}}"};
mstch::map context{
{"yay", std::string{"Yay!"}},
{"bold", mstch::lambda{[](const std::string& text, mstch::renderer render) {
return "<b>" + render(text) + "</b>";
}}}
};
std::cout << mstch::render(view, context) << std::endl;
```
The output will be:
```html
<b>Yay! :)</b>
```
### Objects