简体   繁体   中英

how to highlight string in a string in a laravel blade view

Somewhere in my template I have this:

{{ $result->someText }}

Now in this text I want to highlight all words that are in the string

{{ $searchString }}

So I thought I create a new blade directive:

{{ @highlightSearch($result->someText, $searchString) }}

Blade::directive('highlightSearch', function($input, $searchString)...

error: missing argument 2

Found out that directives do not except 2 arguments. I tried every workaround that I could find but none worked. They always return the arguments as a plain string, not even passing the actual values.

I tried adding a helper function like explained here: https://stackoverflow.com/a/32430258/928666 . Did not work:

error: unknown function "highlightSearch"

So how do I do this super easy task in laravel? I don't care about the highlighting function, that's almost a one-liner.

The reality is blade directives can't do what you need them to do. Whether or not they should is not a topic I can't help with. However you can instead do this in your service provider:

use Illuminate\Support\Str;

/* ... */

Str::macro('highlightSearch', function ($input, $searchString) {
      return str_replace($searchString, "<mark>$searchString</mark>", $input); 
      //Or whatever else you do
});

Then in blade you can just do:

{!! \Illuminate\Support\Str::highlightSearch($result->someText, $searchString) !!}

I've just tested in Laravel 5.1 it and it works without any problem:

\Blade::directive('highlightSearch', function($input) {
    return "<?php echo strtoupper($input); ?>";
});

in boot method of AppServiceProvider

and in view I can use:

@highlightSearch('test')

and it returns TEST as expected.

Make sure you are using Blade from global namespace, also run

php artisan clear-compiled

to make sure everything is refreshed. If it won't help, you can try running

composer dump-autoload

just in case.

EDIT

I've also tested it with additional argument and it really seems not be working as expected, so the most reasonable would be adding helper file (if you don't have any with simple PHP function) as for example:

function highlight_search($text, $searchString) 
{
   // return whatever you want
}

and later use it it in Blade as any other function like so:

{{ highlight_search('Sample', 'Sam') }}

optionally using

{!! highlight_search('Sample', 'Sam') !!}

if you want highlight_search to output HTML

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM