0

我正在使用Radiant CMS的 Rails 站点上工作,并按照此链接中的第一种方法构建有状态导航。

我正在匹配正则表达式上的 URL 以确定是否显示每个导航链接的活动状态。例如,这里有两个示例导航元素,一个用于 Radiant URL /communications/,一个用于/communications/press_releases/

    <r:if_url matches="/communications\/$/"><li class="bottom-border selected">Communications</li></r:if_url>
    <r:unless_url matches="/communications\/$/"><li class="bottom-border"><a href="/communications">Communications</a></li></r:unless_url>
    <r:if_url matches="/communications\/press_releases/"><li class="bottom-border selected">Press Releases</li></r:if_url>
    <r:unless_url matches="/communications\/press_releases/"><li class="bottom-border"><a href="/communications/press_releases">Press Releases</a></li></r:unless_url>

Press Releases 页面的一切正常——也就是说,当 URL 是/communications/press_releasesPress Releases 导航项时,会适当地获得“已选择”类,并且未选择 Communications 导航项。但是,Communications 正则表达式似乎无法正常运行,因为当 URL/communications/两个元素都没有“选定”类时(因此正则表达式必须无法匹配)。但是,我已经测试过

>> "/communications/".match(/communications\/$/)
=> #<MatchData:0x333a4>

在 IRB 中,如您所见,正则表达式似乎工作正常。这可能是什么原因造成的?

TL;DR:在 Ruby shell"/communications/"中匹配/communications\/$/,但在 Radiant 导航的上下文中不匹配。这里发生了什么?

4

1 回答 1

1

Radiant 的 wiki看来,您不需要/在 regex 周围添加 s 或 escape /s。尝试:

<r:if_url matches="/communications/$"><li class="bottom-border selected">Communications</li></r:if_url>
<r:unless_url matches="/communications/$"><li class="bottom-border"><a href="/communications">Communications</a></li></r:unless_url>
<r:if_url matches="/communications/press_releases/"><li class="bottom-border selected">Press Releases</li></r:if_url>
<r:unless_url matches="/communications/press_releases/"><li class="bottom-border"><a href="/communications/press_releases">Press Releases</a></li></r:unless_url>

幕后发生的事情是 Radiant 调用Regex.new字符串 in matches,因此您之前尝试匹配的正则表达式是这个:

 Regexp.new '/communications\/$/'
# => /\/communications\/$\// 

这转化为“斜线通信斜线行尾斜线”,我真的怀疑这是你想要的。

^Ruby 正则表达式的有趣之处在于 start( ) 和 end of line( $) 以及 start( \A) 和 end of string( )都有符号\Z。这就是为什么有时你会看到人们在他们的正则表达式中使用\A和。\Z

于 2010-10-11T20:06:08.597 回答