Cakephp2でページ毎のjsタグが散らばるので一括管理する

どのページにどのタグを埋めたか煩雑になるのでエレメントとヘルパーで管理する
ヘッダーでなくbodyの最後に埋めるタグがややこしくなったためテコ入れ。

Google Tag Manager使えよってコメントはなしで。


// View/Elements/body_tags.ctp でタグと読み込みページ設定

<?php
  // タグ毎に読み込むコントローラーとビューの指定
  // ['Controller'=>['action1', 'action2']];
  // のように配列で指定

  $yahoo = ['Goods'=>['index','detail'] ];
  $facebook = '*'; // 
  $user_trace = '*';
  $client_lp= ['Pages'=>['home'], 'Goods'=>['index', 'detail'], 'Contacts'=>['index']];
?>

<?php if( $this->Tags->is_able_tag($yahoo)): ?>
<!-- yahoo tag -->
  <script>
  ~~~~~
  </script>
<!--// yahoo tag -->
<?php endif ?> 

<?php if( $this->Tags->is_able_tag($facebook)): ?>
<!-- facebook tag -->
  <script>
  ~~~~~
  </script>
<!--// facebook tag -->
<?php endif ?> 

<?php if( $this->Tags->is_able_tag($user_trace)): ?>
<!-- user_trace tag -->
  <script>
  ~~~~~
  </script>
<!--// user_trace tag -->
<?php endif ?> 

// View/Helper/TagsHelper.php で判定の処理部分

<?php
App::uses('AppHelper', 'View/Helper');

class TagsHelper extends AppHelper {
    function is_able_tag($service){
      return $service==='*' || (isset($service[$this->name]) && isset(array_flip($service[$this->name])[mb_strtolower($this->action)]));
    }
}

// View/Layouts/default.ctp でエレメント読み込み

<?php

~~~~
$this->element('body_tags');
</body>

// Controller/AppController.php でヘルパー読み込み

<?php
class AppController extends Controller {
    public $helpers = ['Tags'];

余談 TagsHelperの解説

改行して訳し下してみました。

<?php
App::uses('AppHelper', 'View/Helper');

class TagsHelper extends AppHelper {
    function is_able_tag($service){
      return $service==='*'  // '*'だったらtrueで終了->常に読み込み
      || // '*'じゃなかったら 
      (
        isset($service[$this->name]) // 今のコントローラー名がキーになっていて
        &&  //かつ
        isset(
          array_flip($service[$this->name])  // その値の配列とkeyとvalueを入れ替えた時
          [strtolower(  // 念のため小文字にした
            $this->action  // アクション名が
          )] // keyになったものが  
        ) // 存在している
      );  //ならばtrue
    }}

isset(array_flip($array)[$value])
はin_arrayと同じく配列に値が含まれているか検索している。
こちらの方が早いので、valueに重複がない配列の際はおすすめ。

コントローラー名とアクション名については前回の記事をごらんあれ。