nchristiansen's avatar

How do I Get the Current File in a Blade Template?

Background:

I am rebuilding portions of a website into Laravel 5.2. I would like to leverage an existing translation database/architecture from the old site (42 languages in 50+ countries). Time constraints do not allow me to overhaul the translation system.

Part of this architecture depends on getting a filename for the translation. This is because the same English text can be translated differently in different parts of the site depending on the country due to legal reasons.

I would like to do something like:

@include('translation', ['page' => resource_path('views/path/to/pre-compiled/view.blade.php')])

Only I would like to generate the page location instead of hard coding it.

Problem:

I can't seem to find a reliable way to get the pre-compiled view's path.

I cant use ['page' => __DIR__] because that would point to the compiled and cached view file.

I can't use $_SERVER['SCRIPT_NAME'] that will always be the same like 'public/index.php'.

I can't use the URL or $_SERVER['PHP_SELF'] as the generated page from the URL is made up of many different partials. And doing so will make the translation database have way too many duplicates.

I tried using ['page' => $this->getCompiler()->getPath()] but that only returns the filename when it needs to be compiled, when it is just loading from the cache this returns blank. While I could disable caching site wide it is not a good solution.

Question:

How can I reliably get the pre-compiled filename of a blade template file?

0 likes
1 reply
nchristiansen's avatar
nchristiansen
OP
Best Answer
Level 2

I fixed my problem I extended the Blade compiler as so:

    Blade::extend(function ($view, $compiler) {
        $path = $compiler->getPath();

        if (strpos($path, 'views/translation.blade.php') !== false) {
            return $view;
        }

        $app_path = app_path();

        $path = str_replace($app_path, '', $path);

        $view = "@include('translation', ['domain' => '$path'])\n$view";

        return $view;
    });

Please or to participate in this conversation.