0

I have a template where I want to generate an anchor to the base URL of my application. In my case the method which handles this is FrontController::index().

If it was just a simple link, I can easily do this inside a template:

<?= $this->Html->link('Home', ['controller' => 'Front', 'action' => 'index']); ?>

However, instead of just a simple link with the text "Home" I want to wrap an anchor tag around some other markup. The output I want in plain HTML (not using Cake's helper methods) would be:

 <a href="/">
     <img class="app-logo" src="/app-logo.png"> 
     <span class="app-name">App name</span>
 </a>

I've read How to get the base Url in cakephp? and none of the methods in there work:

echo $this->webroot; // produces 'false'
echo Router::url('/'); // produces 'Class 'App\Controller\Router' not found`

CakePHP 3.5.13

Andy
  • 5,142
  • 11
  • 58
  • 131

1 Answers1

1

You can use the Router Class

<a href="<?= \Cake\Routing\Router::url(['controller' => 'Front', 'action' => 'index']) ?>">
    <img class="app-logo" src="/app-logo.png"> 
    <span class="app-name">App name</span>
</a>

Edit: CakePHP 3.x uses Namespaces. You have to use the fully qualified class name or add a use statement to the top of your script.

echo \Cake\Routing\Router::url(...);

or

use Cake\Routing\Router;

echo Router::url(...);
jbe
  • 1,722
  • 1
  • 12
  • 20
  • You can also use the `link` function, replacing `'Home'` with your desired content (which can in turn be generated with HTML helper functions, if you want), and adding `['escape' => false]` after the URL parameter. – Greg Schmidt Jul 11 '18 at 02:06