Yii ブログシステム作成(14)

タグクラウドポートレットの作成

各タグに属する記事の一覧を表示する
タグが多く含まれるほどリンクの文字を大きくする

TagCloudクラスの作成

タグを表示処理するための”TagCloud.php”ファイルを作成する
格納先は【/blog/protected/components/】

<?php

Yii::import('zii.widgets.CPortlet');

class TagCloud extends CPortlet
{
  public $title = 'Tags';
  public $maxTags = 20;
  
  /**
   * 
   * タグクラウドをレンダリング
   * 
   **/
  protected function renderContent()
  {
    $tags = Tag::model()->findTagWeights($this->maxTags);
    
    foreach($tags as $tag=>$weight)
    {
      $link = CHtml::link(CHtml::encode($tag), array('post/index', 'tag'=>$tag));
      
      echo CHtml::Tag(
        'span',
        array(
          'class'=>'tag',
          'style'=>"font-size:{$weight}pt",
        ),
        $link."\n"
      );
    }
  }
}

あまり多くのHTMLタグを含まないため『UserMenu』ポートレットと異なり
『TagCloud』ポートレットはビューを使用しない代わりに『renderContent()』メソッドで処理する

それぞれのタグは、記事のインデックスページへのハイパーリンクとして表示する
タグが頻繁に主具現するほどフォントサイズが大きくなる

TagCloudポートレットの使用

“colimn2.php”ファイルを修正する

  ・・・
  <div id="sidebar">
  <?php
    // "UserMenu"ポートレットを表示
    if(!Yii::app()->user->isGuest) $this->widget('UserMenu');
  ?>
  <?php
    $this->widget(
      'TagCloud',
      array(
        'maxTags'=>Yii::app()->params['tagCloudCount'],
      )
    );
  ?>
  </div><!-- sidebar -->
  ・・・

■実行画面
【http://loaclhost/index.php?r=post/】にアクセス

yii051

※URLの書き換えについては次章で解説する

参考サイト:
http://www.yiiframework.com/doc/blog/1.1/ja/portlet.tags

Comments are closed.