2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[baserCMS]現在のURL判定に isCurrentUrl($url) を使うと少しだけラクになる

Last updated at Posted at 2015-02-25

現在アクセスしているURLを見て表示切替え。。。よくあるケースです。
そんなときの判定の仕方。

発生状況

  1. テーマ側(Layoutとか)で、今アクセスしているURLを見て、表示切替えしたいなぁ
  2. よし!getHere()の出番だ!
  3. わぁ!判定2つ要る。。。

環境

  • baserCMS 3.0.6.1
  • PHP 5.4.19

URL判定サンプル

<?php $currentUrl = $this->BcBaser->getHere() ?>
<?php if ($currentUrl == '/nowurl/' || $currentUrl == '/nowurl/index'): ?>
/nowurl/ または /nowurl/index にアクセスしているときに表示する
<?php else: ?>
/nowurl/ または /nowurl/index 以外にアクセスしているときに表示する
<?php endif ?>

他にも、現在のURLを取得したいときに使えるもの。

// 現在アクセスしているURLが文字列で返って来る
$this->request->here

$this->BcBaser->url()

Router::url()

というように、URLの末尾が「/」で終わるものは、「/index」の場合においても判定しておく必要があります。

対処策 isCurrentUrl($url)

そんなときに使える判定方法のサンプルは以下。

<?php if ($this->BcBaser->getHere() == $this->BcBaser->isCurrentUrl('/nowurl/')): ?>
/nowurl/ にアクセスしているときに表示する
<?php else: ?>
/nowurl/ 以外にアクセスしているときに表示する
<?php endif ?>

これで「/index」の場合を判定する必要がなくなります。
BcBaser::isCurrentUrl($url) では、スラッシュのみの場合と、スラッシュ+index の場合は、同一のURLとして判定します。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?