正确的嵌入式 Ruby 代码编写

发布于 2024-09-09 04:22:46 字数 431 浏览 5 评论 0原文

我正在尝试写这个:

 %meta{ :name => "keywords", :content => "#{@page_city}, #{truncate_words(@page_keywords, 7) || 'Meta, Words, Are, Dope, For, SEO'}"}

基本上它会查看是否有一个本地页面具有页面城市或关键字,并将它们添加为元关键字。如果没有,则说明是后者。

这是可行的,但唯一的问题是出现了 page_city 之后的第一个逗号。所以现在它看起来是..

 <meta content=', Meta, Words, Are, Dope, For, SEO' name='keywords' />

有谁知道如何将“,”也包含到嵌入变量中吗?

I am trying to write this :

 %meta{ :name => "keywords", :content => "#{@page_city}, #{truncate_words(@page_keywords, 7) || 'Meta, Words, Are, Dope, For, SEO'}"}

Basically it sees if there is a local page that has a page city or keywords and adds those as they meta keywords. If it doesn't, it says the latter.

This works, but the only problem is that first comma after page_city is appearing. So right now it appears as ..

 <meta content=', Meta, Words, Are, Dope, For, SEO' name='keywords' />

Does anyone know how to include that "," into the embedded variables as well?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

飘过的浮云 2024-09-16 04:22:46

在这种情况下,您通常可以依靠 Array:

- default_keywords = %w[ Meta Words Are Dope For SEO ]
- meta_content = [ @page_city, (truncate_words(@page_keywords, 7) || default_keywords) ]

%meta{ :name => "keywords", :content => meta_content.flatten.compact.join(',') }

Array#compact 删除所有 nil 值以避免插入额外的逗号。

You can usually lean on Array for situations like this:

- default_keywords = %w[ Meta Words Are Dope For SEO ]
- meta_content = [ @page_city, (truncate_words(@page_keywords, 7) || default_keywords) ]

%meta{ :name => "keywords", :content => meta_content.flatten.compact.join(',') }

Array#compact strips out all nil values to avoid inserting extra commas.

感性不性感 2024-09-16 04:22:46

你总是可以这样做:

#{@page_city + ', ' if @page_city}

就我个人而言,我可能会采取完全不同的方法:

@arg1 = 'foo'
@arg2 = 'bar'
@arg3 = 'baz'
[@arg1, @arg2, @arg3].join(", ")    # => "foo, bar, baz"

You could always just do this:

#{@page_city + ', ' if @page_city}

Personally, I would probably go for a different approach to this altogether:

@arg1 = 'foo'
@arg2 = 'bar'
@arg3 = 'baz'
[@arg1, @arg2, @arg3].join(", ")    # => "foo, bar, baz"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文