//方式一:
res.set_attr("variable","hello,world");
//方式二:
json jsondata;
jsondata["code"]=0;
jsondata["msg"]="ok";
res.write_view("./tpl/login.html", jsondata,false);
对json数组的遍历
{% for item in list %}
<p>@{item.name}</p>
{% endfor %}
// 数组元素的访问
<div>@{list.0.name}</div>
// 获取list长度
<div>@{length(list)}</div>
// 获取list中的第一个或最后一个元素
<div>@{first (list)}</div>
<div>@{last (list)}</div>
//列表排序
<div>@{sort([3,2,1])}</div>
<div>@{sort(list)}</div>
// 获取list中的最大最小值
<div>max([1,3,2])</div>
<div>min([3,1,2])</div>
<div>min(list)</div>
// 还可以通过关键字loop访问当前循环的属性和值
{% for item in list %}
<p>
<span>@{loop.index }</span>
<span>@{loop.index1 }</span>
<span>@{loop.is_first }</span>
<span>@{loop.is_last }</span>
<span>@{item.name}</span>
</p>
{% endfor %}
// 多重循环中,嵌套的循环中可以通过loop.parent访问父层循环的loop,以此类推loop.parent.parent
{% for item in list %}
{% for item0 in item %}
<p>@{item0.abc}</p>
{% endfor %}
{% endfor %}
对json对象的遍历
{% for key, value in object %}
<p>
<span>@{key}</span>
<span>:</span>
<span>@{value}</span>
</p>
{% endfor %}
获取一个循环区间
{% for i in range(4) %}
<div>@{ loop.index1 }</div>
{% endfor %}
@{downpath}
== , > , >= , < , <= , != , 逻辑与 and , 逻辑或 or , 逻辑非 not
{% if variable == true %}
<div>如果variable是true则显示</div>
{% endif %}
{% if variable in list %}
<div>variable:"a",list:["a","b"]</div>
{% endif %}
{% if variable == null %}
{% endif %}
{% if ... %}
{% else if ... %}
{% else %}
{% endif %}
// 判断对象中是否存在某键名
{% if exists(\"variable\") %}
存在
{% endif %}
{% if existsIn(variable,\"time\") %}
<div>variable对象中是否存在key为time的键值对</div>
{% endif %}
// 判断值的类型
<div>@{isString(variable)}</div>
<div>@{isArray(variable)}</div>
{% include \"footer.html\" %}
<div>
#(
{% for item in list %}
{% endfor %}
)#
<div>
<div>@{upper(variable)}</div>
<div>@{lower(variable)}</div>
<div>@{odd(42)}</div>
<div>@{even(42)}</div>
@{ round(3.1415, 2) }
<div>round(3.1415, 0)</div>
<div>round(3.1415, 2)</div>
<div>@{divisibleBy(42,7)}</div>
<div>@{int(\"2\") == 2 } </div>
<div>@{float(\"1.8\") > 2}</div>
<div>1</div>
{#
Todo...
#}
<div>@{default(notexists, \"默认值\")}</div>
通过http_server类的add_view_method方法可以给模板渲染引擎增加处理方法
add_view_method 参数解释
参数一: 定义的方法名:string
参数二: 方法参数个数
参数三: 为该方法注册的cpp方法,其参数为 inja::Arguments const& args,返回值为可以隐式转换成json对象的类型
server.add_view_method("str2int", 1, [](inja::Arguments const& args) {
auto i = std::atoi(args[0]->get<std::string>().data());
return std::string("transform:") + std::to_string(i);
});
<div>@{str2int(\"123\")}</div>
通过response类中的view_environment方法获取模板渲染引擎的句柄 ,注意此设置只针对当前请求的返回,不是全局的
res. view_environment().set_expression("@{","}")