我很难在我的运动应用中添加圆形图。 是否可以将 morris.js 值设置为我的控制器中的变量? 我在控制器中有 @diet_calories 变量,我想显示Carbs - >蛋白质 - >脂肪 60% - > 20% - > 20%关系。如果我在脚本标签中设置碳水化合物的值(值:@diet_calories * 0.6 ),它就无法正常工作。 你有什么建议可以解决这个问题吗?
application.html.erb:
<script>
new Morris.Donut({
element: 'diet-circle',
data: [
{ label: "Carbs", value: @diet_calories * 0.6 },
{ label: "Protein", value: @diet_calories * 0.2 },
{ label: "Fat", value: @diet_calories * 0.2 }
]
});
</script>
info_controller.rb:
def diet
if current_user.activity == "Sedentary"
if current_user.goals == "Lose Weight"
@diet_calories = ((@bmr * 1.1) - 300).to_i
elsif current_user.goals == "Maintain Weight"
@diet_calories = (@bmr * 1.1).to_i
elsif current_user.goals == "Add some weight"
@diet_calories = ((@bmr * 1.1) + 300).to_i
end
elsif current_user.activity == "Low"
if current_user.goals == "Lose Weight"
@diet_calories = ((@bmr * 1.5) - 300).to_i
elsif current_user.goals == "Maintain Weight"
@diet_calories = (@bmr * 1.5).to_i
elsif current_user.goals == "Add some weight"
@diet_calories = ((@bmr * 1.5) + 300).to_i
end
elsif current_user.activity == "Medium"
if current_user.goals == "Lose Weight"
@diet_calories = ((@bmr * 1.7) - 300).to_i
elsif current_user.goals == "Maintain Weight"
@diet_calories = (@bmr * 1.7).to_i
elsif current_user.goals == "Add some weight"
@diet_calories = ((@bmr * 1.7) + 300).to_i
end
elsif current_user.activity == "High"
if current_user.goals == "Lose Weight"
@diet_calories = ((@bmr * 2.1) - 300).to_i
elsif current_user.goals == "Maintain Weight"
@diet_calories = (@bmr * 2.1).to_i
elsif current_user.goals == "Add some weight"
@diet_calories = ((@bmr * 2.1) + 300).to_i
end
end
diet.html.erb:
<div id="diet-circle"></div>
答案 0 :(得分:1)
您可以通过进行此更改来实现此目的 在你的application.html.erb
中<script>
var diet_calories = <%= @diet_calories %>
new Morris.Donut({
element: 'diet-circle',
data: [
{ label: "Carbs", value: diet_calories * 0.6 },
{ label: "Protein", value: diet_calories * 0.2 },
{ label: "Fat", value: diet_calories * 0.2 }
]
});
</script>
要进一步了解将变量从rails传递到javascript,请查看this railscast.
答案 1 :(得分:1)
尝试:
<script>
new Morris.Donut({
element: 'diet-circle',
data: [
{ label: "Carbs", value: <%= @diet_calories %> * 0.6 },
{ label: "Protein", value: <%= @diet_calories %> * 0.2 },
{ label: "Fat", value: <%= @diet_calories %> * 0.2 }
]
});
</script>
.erb
代表嵌入式RuBy 。
在用于评估Ruby代码的.erb
文件中(示例使用在控制器中设置的实例变量),您需要使用<%= ruby code %>
您可以阅读Erb模板here
的简介