我们已经找到了很多答案,但并不完全了解它们(或者说是的 strpos
手册页面)所以,如果这个问题已经回答了,很抱歉。
考虑以下的URLs...
http://www.domain.com/whats-on/show-name/
http://www.domain.com/whats-on/show-name/events
以及我们如何应用 .active
在以下列表项标记中,类...
<li>
<a class="<?= (strpos($_SERVER['REQUEST_URI'], '/whats-on') === 0 ? 'active' : ''); ?>" href="<?= $ShowWhatsOn; ?>">What's on</a>
</li>
<li>
<a class="<?= (strpos($_SERVER['REQUEST_URI'], '/events') === 0 ? 'active' : ''); ?>" href="<?= $ShowEvents; ?>">Events</a>
</li>
What's On在What's On页面得到了活动类,但在Events页面也得到了活动类,因为What's-on也在url:Whats-onshow-nameevents中。
事件永远不会收到主动类
.active
类应用在正确的页面上?我们正试图让这个菜单标记简短,所以希望有办法在一行上完成?
如果有任何正确的帮助或指导,我们将非常感激。
欢呼
本
功能 strpos
给出了一根线(针)在另一根线(干草堆)中的位置。所以通过做
strpos($_SERVER['REQUEST_URI'], '/whats-on') === 0
您正在检查是否有 REQUEST_URI
以 "whats-on "开头(位于0位置)。由于两个URL都是以 "wats-on "开头的,所以第一个项目将始终处于活动状态,而第二个项目永远不会。
一个解决方法是添加一个 "事件 "的检查。
<li>
<a class="<?= (strpos($_SERVER['REQUEST_URI'], '/whats-on') === 0 && strpos($_SERVER['REQUEST_URI'], '/events') === false ? 'active' : ''); ?>" href="<?= $ShowWhatsOn; ?>">What's on</a>
</li>
<li>
<a class="<?= (strpos($_SERVER['REQUEST_URI'], '/whats-on') === 0 && strpos($_SERVER['REQUEST_URI'], '/events') !== false ? 'active' : ''); ?>" href="<?= $ShowEvents; ?>">Events</a>
</li>
虽然这对你的模板来说有点啰嗦, 所以你可能想把逻辑分解成一个函数,比如: isActive()
.
好了,为了我以后的参考(和其他人),我是这样解决的。
我在我的CMS的helpers目录下做了这个,并将其命名为npe_nav.php(如果使用Concrete5 CMS,不要将文件命名为navigation.php,因为这个名字被c5占用了,所以我没有用)。
// Get URL segments
public function getURLSegments() {
return explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
}
// Get a specific URL segment
// Takes a number which corisponds to a segment in the URL e.g. consider:
// http://www.domain.com/whats-on/show-name/events
// $navHelper->getURLSegment(1); will return whats-on
// $navHelper->getURLSegment(3); will return events
public function getURLSegment($n) {
$segs = $this->getURLSegments();
return count($segs) > 0 && count($segs) >= ($n-1)?$segs[$n]:'';
}
在Concrete5中,我是这样加载的(包名是指这个工具在CMS中保存的包)。
// Load nav helper
$navHelper = Loader::helper('npe_nav','package-name');
这也会检查第三段是否为空,然后再应用 .active
因为 /whats-on/
出现在本节的所有URL中--所以不希望它在其他页面上活动。
<li>
<a class="<?= (($navHelper->getURLSegment(1) == 'whats-on') && (is_null($navHelper->getURLSegment(3))) ? 'active' : ''); ?>" href="<?= $ShowWhatsOn; ?>">What's on</a>
</li>
对于URL。http:/www.domain.comwhats-onshow-nameevents第3部分的其他网页
<li>
<a class="<?= ($navHelper->getURLSegment(3) == 'events' ? 'active' : ''); ?>" href="<?= $ShowEvents; ?>">Events</a>
</li>