为何向Mustache模板传入整数会引发错误?
Mustache模板渲染整数失败的原因分析
代码场景
你在Mustache模板相关代码中做了如下定义:
参数定义
# Ruby环境 params = { "a": rand(20) }
# Python环境 params = { "a": rand(20) }
模板与渲染代码
你尝试直接将计算结果作为模板内容传入渲染方法:
# Ruby环境 exercise = { "solution": params[:a] + 1 } # 渲染执行代码 puts Mustache.render(exercise[:solution], params)
# Python环境 exercise = { "solution": params["a"] + 1 } # 渲染执行代码 print(chevron.render(template=exercise["solution"], data=params))
报错信息
- Ruby环境报错:
no implicit conversion of Integer into String (TypeError)
- Python环境报错:
AttributeError: 'int' object has no attribute 'split'
原因
Mustache类库(包括Ruby的Mustache和Python的chevron)的render方法第一个参数要求传入字符串类型的模板内容。你直接传入了params[:a]+1/params["a"]+1计算得到的整数,库会把这个整数当作模板字符串去解析:
- Ruby中,库内部处理模板时需要字符串类型,尝试将整数转换为字符串时触发类型转换错误;
- Python中,库会调用字符串的
split方法来解析模板结构,但整数没有该方法,因此抛出属性错误。
解决办法
将计算后的整数转换为字符串后再传入render方法:
- Ruby:
(params[:a] + 1).to_s - Python:
str(params["a"] + 1)
内容的提问来源于stack exchange,提问作者somenxavier
相关产品推荐
相关产品推荐

