Creating Tag Cloud Portlet

Tag cloud displays a list of post tags with visual decorations hinting the popularity of each individual tag.

1. Creating TagCloud Class

We create the TagCloud class in the file /wwwroot/blog/protected/components/TagCloud.php. The file has the following content:

class TagCloud extends CPortlet
    public $title='Tags';
    public $maxTags=20;
    protected function renderContent()
        foreach($tags as $tag=>$weight)
            $link=CHtml::link(CHtml::encode($tag), array('post/index','tag'=>$tag));
            echo CHtml::tag('span', array(
            ), $link)."\n";

Unlike the UserMenu portlet, the TagCloud portlet does not use a view. Instead, its presentation is done in the renderContent() method. This is because the presentation does not contain much HTML tags.

We display each tag as a hyperlink to the post index page with the corresponding tag parameter. The font size of each tag link is adjusted according to their relative weight among other tags. If a tag has higher frequency value than the other, it will have a bigger font size.

2. Using TagCloud Portlet

Usage of the TagCloud portlet is very simple. We modify the layout file /wwwroot/blog/protected/views/layouts/column2.php as follows,

<div id="sidebar">
    <?php if(!Yii::app()->user->isGuest) $this->widget('UserMenu'); ?>
    <?php $this->widget('TagCloud', array(
    )); ?>

Total 3 comments

#4357 report it
majin sensei at 2011/06/28 01:11pm

findTagWeights can be found on /wwwroot/yii/demos/blog/protected/models/Tag.php

#789 report it
Chris83 at 2010/02/27 07:30pm
What tagCloudCount?

You need to modify your config/main.php and add a row under 'params' which is

#790 report it
Chris83 at 2010/02/27 07:27pm
What getTagWeigths?

I could not find the function getTagWeigths so I wrote one:

public function findTagWeights($maxTags=20)
   $criteria = new CDbCriteria();
   $criteria->limit = $maxTags;
   $tags = Tag::model()->findAll($criteria);
   $tagWeigths = array();
   foreach($tags as $tag)
      $weigth = $tag->frequency+8;
      $weigth = $weigth>=12 ? 12 : $weigth;
      $tagWeigths[$tag->name] = $weigth;
   return $tagWeigths;

Hope this helps.

Leave a comment

Please to leave your comment.