Bootstrap Glyphicons and Font Awesome in CakePHP 3

Written by James McDonald

January 22, 2018

This is how I use both bootstrap glyphicons and the font awesome fonts in cake with some simple helper methods.

You first need to copy your font awesome files to webroot/webfonts and glyphicons to webroot/fonts and the respective css files to webroot/css and include them in your views.

You need to add the glyphicoons & fontawesome css to the >head< of your src/Template/Layout/default.ctp


// first set your CSS assets to a block

<?php
$this->Html->css([
    'bootstrap.min',
    'bootstrap.icon-large.min',
    'fontawesome-all.min',
    'clam' // local custom CSS
  ], 
  [
    'block' => true
  ])
?>

// then use fetch to place your block of CSS
<?= $this->fetch('css') ?>

// you end up with

<link rel="stylesheet" href="/css/bootstrap.min.css"/><link rel="stylesheet" href="/css/bootstrap.icon-large.min.css"/><link rel="stylesheet" href="/css/fontawesome-all.min.css"/>

First create a file src/View/Helper/IconHelper.php with the following content


<?php 
namespace App\View\Helper; 
use Cake\View\Helper\HtmlHelper; 
class IconHelper extends HtmlHelper { 

// initialize() hook is available since 3.2. For prior versions you can 
// override the constructor if required. 

  public function initialize(array $config) { 

  } 

  public function gIcon($icon) { 
    $format = 'glyphicon glyphicon-%s'; return $this->tag('span', '', [ 'class' => sprintf($format, $icon)]);
  }

  public function faIcon($icon)
  {
    return $this->tag('i', '', [ 'class' => $icon ]);
  }

}


The enable it by adding the following to the initialize function of src/View/AppView.php


class AppView extends View
{

    /**
     * Initialization hook method.
     *
     * Use this method to add common initialization code like loading helpers.
     *
     * e.g. `$this->loadHelper('Html');`
     *
     * @return void
     */
    public function initialize()
    {

  			$this->loadHelper('Icon');  

    }
}

Then in any of your *.ctp view files under src/Template/


<?php // for font awesome ?>

<td class="text-center"><?= $part->active ? $this->Icon->faIcon('fas fa-check') : "" ?></td>

<?php // for bootstrap glyphicons ?>

<td class="text-center"><?= ( (bool) $person->active) ? $this->Icon->gIcon('ok'): ''; ?></td>

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.

You May Also Like…