我想显示用户当前的婴儿步骤和说明(来自Dave Ramsey's 7 Baby Steps)。例如,如果用户在Baby Step 3上,则模板应呈现:
<h1>Your Current Baby Step</h1>
<p>You are on <em>Baby Step 3</em>. You should:</p>
<p><strong>Save 3–6 Months of Expenses in a Fully Funded Emergency Fund</strong></p>
我写了一个长的if语句,该语句有效但很笨重:
[#assign babyStep = 3]
<h1>Your Current Baby Step</h1>
<p>You are on <em>Baby Step ${babyStep!}</em>. You should:</p>
<p><strong>
[#if babyStep == 1]
Save $1,000 for Your Starter Emergency Fund
[#elseif babyStep == 2]
Pay Off All Debt (Except the House) Using the Debt Snowball
[#elseif babyStep == 3]
Save 3–6 Months of Expenses in a Fully Funded Emergency Fund
[#elseif babyStep == 4]
Invest 15% of Your Household Income in Retirement
[#elseif babyStep == 5]
Save for Your Children’s College Fund
[#elseif babyStep == 6]
Pay Off Your Home Early
[#elseif babyStep == 7]
Build Wealth and Give
[/#if]
</strong></p>
如何简化和提高这段代码的可读性?
答案 0 :(得分:0)
创建一个sequence的婴儿步骤说明,并通过列表中的索引访问正确的步骤。如果Dave决定添加另一个Baby Step?,那么就像更新序列一样简单!
[#assign babyStep = 3]
<h1>Your Current Baby Step</h1>
<p>You are on <em>Baby Step ${babyStep!}</em>. You should:</p>
[#assign babySteps = [
"Save $1,000 for Your Starter Emergency Fund",
"Pay Off All Debt (Except the House) Using the Debt Snowball",
"Save 3–6 Months of Expenses in a Fully Funded Emergency Fund",
"Invest 15% of Your Household Income in Retirement",
"Save for Your Children’s College Fund",
"Pay Off Your Home Early",
"Build Wealth and Give"
]]
<p><strong>${babySteps[babyStep - 1]!}</strong></p>
请注意,由于FreeMarker序列具有从零开始的索引,因此必须将婴儿步骤编号减去1。