Aridez
Aridez

Reputation: 502

Easier way to create a custom Laravel Blade directive when a string is being concatenated with variables

I created the following blade directive:

    Blade::directive('bundle', function ($component) {
        $string = "\":langs='\" . file_get_contents(base_path() . \"/resources/bundles/\" . App::currentLocale() . \"/$component.json\").\"'\";";
        return ("<?php echo " . $string . "?>");
    });

To better understand what's going on, this is the code that I would like to represent with that string above (but being a Blade directive this is not an option):

$path = base_path() . "\\resources\\bundles\\" . App::currentLocale() ."\\$component.json";
$json = file_get_contents($path);
return "<?php echo \":langs='\" $json \"'\"; ?>

As it is now, the Blade directive above won't work when there are single quotes within the .json file due to the external quotation marks being the single ones too. But in any case, it feels like it's too hard to wrap my head around creating this string, I was wondering, is there an easier way to generate that final string to echo out the result?

Upvotes: 1

Views: 546

Answers (2)

Aridez
Aridez

Reputation: 502

In the end I created a helper function and return a string calling that one function from the blade directive:

Blade::directive('bundle', function ($bundle) {
    return ":langs=\"{{json_bundle_translations($bundle)}}\"";          
});

And then the helper function looks like:

    function json_bundle_translations($bundle)
{
    $path = base_path() . "\\resources\\bundles\\" . App::currentLocale() . "\\$bundle.json";
    return file_get_contents($path);
}

It feels easier to understand rather than having strings within strings inside the directive and it's also giving a function to retrieve the Json alone in case it's needed.

I'll leave this question open for a while to see if someone can come up with a better solution.

Edit: The best way I found to create complex blade directives without having to deal with a lengthy string was just to call a helper method

Upvotes: 0

nmfzone
nmfzone

Reputation: 2903

Based on your information, this is what I've got:

Blade::directive('bundle', function ($component) {
    $encoding = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT;
    $component = trim($component, "'\" ");

    $string = sprintf(
        '":langs=\'" . json_encode(json_decode(file_get_contents(%s), true), %d) . "\'"',
        'resource_path("bundles/" . App::getLocale() . "/' . $component . '.json")',
        $encoding
    );

    return ('<?php echo ' . $string . '?>');
});

Upvotes: 1

Related Questions