Home > Enterprise >  How to display HTML output from PHP return function
How to display HTML output from PHP return function

Time:01-01

I have the function displayName in php that returns a string like this:

"${name} <i class=\"fa fa-check-circle\" style=\"font-size:22px;color:green\"/>"
public function getDisplayName()
{
    /** @var Module $module */
    $module = Yii::$app->getModule('user');

    if ($module->displayNameCallback !== null) {
        return call_user_func($module->displayNameCallback, $this);
    }

    $name = '';

    $format = Yii::$app->settings->get('displayNameFormat');

    if ($this->profile !== null && $format == '{profile.firstname} {profile.lastname}') {
        $name = $this->profile->firstname . ' ' . $this->profile->lastname;          
        if (($this->profile->user_id == 1)){
            $check_mark = '<i  style="font-size:22px;color:green"/>';
        }
        else{
            $check_mark = '';   
        }
    }

    // Return always username as fallback
    if ($name == '' || $name == ' ') {
        return $this->username;
    }

    return $name . ' '.  $check_mark;
}

I call that function in my component like this:

public function run() {
  return $this->render('containerProfileHeader', [ 'title' => $this->title, ]);
}
    
<h1 ><?= Html::encode($title) ?></h1>
    
public function init() {
  parent::init();
  $this->title = $this->container->getDisplayName();
}

The expectation was having the string returned by getDisplayName() rendered in the html as is but instead I've got this:

Output Screenshot

CodePudding user response:

Issue resolved from

<?= Yii::$app->formatter->asHtml($title); ?>

Used

Yii::$app->formatter->asHtml instead of Html::encode

CodePudding user response:

You should try echo() functions in the return function. I hope it will work.

  • Related