T1000
T1000

Reputation: 948

How to append a parameter to current page using CHtml::link?

Using Yii, and trying to append a Lang=xx to the end of the current page url and present it on the page.

I put the below code in the protected/views/layout/main.php

<?php echo CHtml::link('English', array('','lang'=>'en'), array('class'=>'en')) ?>
<?php echo CHtml::link('中文', array('','lang'=>'tw'), array('class'=>'tw')) ?>
<?php echo CHtml::link('日本語', array('','lang'=>'jp'), array('class'=>'jp')) ?>

With standard pages like "/site/index", or controller action pages like "/site/contact", they work fine. But with the standard static pages like "site/page?view=about", it's not working. The url expected should be something like "site/page?view=about&lang=tw", but instead, it gives me "site/page?lang=tw".

How can I fix that?

Upvotes: 0

Views: 3326

Answers (2)

T1000
T1000

Reputation: 948

I ended up doing it with langhandeler extension and url rules and map [site]/[path]?lang=[language code] to [site]/[language code]/[path]

And then I coded the links like below:

        <?php 
        $request = $_SERVER['REQUEST_URI'];
        $path_a = explode("/",$request);
        $haveLang = isSet($_GET["lang"]);
        $uri = ($haveLang?
                substr($request, strlen($path_a[1])+1) //strip language prefix and the slash
                :$request);                               //don't process if the page is in default language
        echo CHtml::link(CHtml::encode(Yii::app()->name), CHtml::normalizeUrl(($haveLang?'/'.$_GET["lang"].'/':'/')), array('id'=>'logo')); 
        ?>
          <div id="lang_switch">                  
            <?php
            echo CHtml::link('English', CHtml::normalizeUrl($uri), array('class'=>'en')); //no need to add default language prefix
            echo CHtml::link('中文', CHtml::normalizeUrl('/tw'.$uri), array('class'=>'tw'));
            echo CHtml::link('日本語', CHtml::normalizeUrl('/jp'.$uri), array('class'=>'jp'));
            ?>
          </div>

that pretty much solved my problem. I hope this could help out someone else in the future.

Upvotes: 1

Jaison Justus
Jaison Justus

Reputation: 2793

you can give chtml link like this

$language = 'en';
CHtml::link("English", array('site/about/lang/' . $language));

site/about/lang/en = controller/action/lang/en

i hope this will help you.

Upvotes: 0

Related Questions