我该怎么写“文字"?一次并同时检查path_info是否包含"A"? [英] How can I do to write "Text" just once and in the same time check if the path_info includes 'A'?
问题描述
- if !request.path_info.include? 'A'
%{:id => 'A'}
"Text"
- else
"Text"
文本"被写入两次.我该怎么做只写一次,同时检查path_info是否包含"A"?
"Text" is written twice. How can I do to write it just once and in the same time check if the path_info includes 'A'?
推荐答案
有两种方法可以做到这一点.使用部分,或使用 content_for块:
There are two ways to do this. Using a partial, or using a content_for block:
如果文本"较长或是重要的子树,则可以将其提取为部分文本.这会使您的代码变干一点.在给出的示例中,这似乎有些矫kill过正.
If "Text" was longer, or was a significant subtree, you could extract it into a partial. This would DRY up your code a little. In the example given this would seem like overkill.
在这种情况下,更好的方法是使用content_for块,如下所示:
The better way in this case would be to use a content_for block, like so:
- if !request.path_info.include? 'A'
%{:id => 'A'}
=yield :content
- else
=yield :content
-content_for :content do
Text
在这里,我们在两个地方都产生了content_for块,从而消除了重复文本"的需要.在这种情况下,我会说这是您最好的解决方案.
Here we yield to the content_for block in both places, removing the need to duplicate "Text". I would say in this case this is your best solution.
这篇关于我该怎么写“文字"?一次并同时检查path_info是否包含"A"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!