From 25b002bacb87a58f09a1b219ef3f4ea4803af3d8 Mon Sep 17 00:00:00 2001 From: Daniel Sipka Date: Fri, 24 Apr 2015 15:51:41 +0200 Subject: [PATCH] lambdas documentation --- README.md | 52 ++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 48 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 33f9f63..7f6a12b 100644 --- a/README.md +++ b/README.md @@ -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 Chris Mark Scott @@ -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 "" + render(text) + ""; + }}} +}; + +std::cout << mstch::render(view, context) << std::endl; +``` + +The output will be: + +```html +Yay! :) +``` ### Objects