2

I could get and set $baseUrl like this in every route,

<?php
$app->get('/sign-in', function ($request, $response, $args) {
    $uri = $request->getUri();
    $baseUrl = $uri->getBaseUrl();

    $this->renderer->render($response, 'sign-in.phtml', $args);
});

But I have to set it in every route for all views.

Is there a way where I can set $baseUrl in a place and use it in every routes/views ?

Jacob Goh
  • 19,800
  • 5
  • 53
  • 73
  • what's your slim mode? – Mansoor H Aug 28 '16 at 08:57
  • In index.php, environment values are already set. like `$_ENV['SLIM_MODE'] = "local";`. if you set local means edit your local.config.php file like `ConfigHelper::write('baseUrl', "http://yyyyyyyy.com");` – Mansoor H Aug 28 '16 at 09:05
  • @MansoorH Sorry, I don't understand. I search through the whole slim skeleton for the terms 'SLIM_MODE', it does not exist anywhere. Can't find local.config.php either. – Jacob Goh Aug 28 '16 at 09:11
  • Possible duplicate of [Slim Framework Base URL](http://stackoverflow.com/questions/11481210/slim-framework-base-url) – Shivam Mathur Aug 29 '16 at 02:44
  • @ShivamMathur that was for Slim v2. – Jacob Goh Aug 29 '16 at 03:05
  • @JacobGoh Router Class has a `setBasePath` method. Use that. https://github.com/slimphp/Slim/blob/3.x/Slim/Router.php#L95 – Shivam Mathur Aug 29 '16 at 04:05

1 Answers1

3

When you register the Twig View helper, also add the $view['baseUrl'] so you can use it in every route:

$container['view'] = function ($c) {
    $view = new \Slim\Views\Twig('templates');

    // Instantiate and add Slim specific extension
    $basePath = rtrim(str_ireplace('index.php', '', $c['request']->getUri()->getBasePath()), '/');
    $view->addExtension(new Slim\Views\TwigExtension($c['router'], $basePath));
    $view['baseUrl'] = $c['request']->getUri()->getBaseUrl();

    return $view;
};

In your Twig file you'll use:

{{ baseUrl }}
Davide Pastore
  • 8,678
  • 10
  • 39
  • 53