我正在开发一个使用辐射CMS的Rails站点,并按照此链接中的第一个方法构建有状态导航。
我正在匹配正则表达式上的URL,以确定是否显示每个导航链接的活动状态。下面是两个示例导航元素,一个用于Radiant /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>对于新闻发布页面,一切都很好--也就是说,当URL是/communications/press_releases时,Press Releases项会适当地获得“Selected”类,并且通信导航项将被取消选择。但是,Communication正则表达式似乎不能正常工作,因为当URL是/communications/时,两个元素都没有“选择”类(因此正则表达式必须匹配)。不过,我已经测试过
>> "/communications/".match(/communications\/$/)
=> #<MatchData:0x333a4>在IRB中,正如您所看到的,正则表达式似乎运行良好。是什么导致了这一切?
TL;DR:"/communications/"与Ruby中的/communications\/$/匹配,但在Radiant导航上下文中不匹配。这里发生了什么事?
发布于 2010-10-11 20:06:08
在辐射维基中,看起来不需要在regexs周围添加/s,也不需要转义/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在matches中的字符串上调用Regex.new,所以您之前试图匹配的正则表达式是这样的:
Regexp.new '/communications\/$/'
# => /\/communications\/$\// 翻译成“斜杠通讯斜杠,行尾斜杠”,我真的很怀疑这是你想要的。
Regexs很有趣,因为它同时存在着开始(^)和行尾($)以及开始(\A)和字符串结束(\Z)的符号。这就是为什么有时你会看到人们在他们的正则表达式中使用\A和\Z。
https://stackoverflow.com/questions/3908877
复制相似问题