简体   繁体   中英

Use of undefined constant post - assumed 'post' - php code with html

Do you know why this code "<a href="{{route('posts.show', ['id' => 'post.id', 'slug' => post.slug])}}" class="btn btn-primary text-white">More</a>" in the code below shows Use of undefined constant post - assumed 'post'?

    $.each(result, function(index, post) {
            newPosts += '<div class="col-12 col-sm-6 col-lg-4 col-xl-3 mb-4">\n' +
'                        <div class="card box-shaddow">\n' +
+'                            <div class="card-body">\n' +
+'                                <h5 class="card-title h6 font-weight-bold text-heading-blue">'+post.name+'</h5>\n' +
+'                            </div>\n' +
'                            <div class="card-footer d-flex justify-content-between align-items-center">\n' +
'                                 <a href="{{route('posts.show', ['id' => 'post.id', 'slug' => post.slug])}}" class="btn btn-primary text-white">More</a>

'       <span class="font-weight-bold font-size-sm text-heading-blue"> </span>\n' +
'                            </div>\n' +
'                        </div>\n' +
'                    </div>';
        });

You cannot use your Javascript post object as a variable in a call to Blade's route() function. Blade will render the template on the server before sending it to the browser, whereas your Javascript code gets executed by your visitor on their computer much later.

One option is to let Blade fill a variable that you can use in Javascript, using dummy values:

var placeholder = "{{route('posts.show', ['id' => 123, 'slug' => 'demo-slug'])}}";

$.each(result, function(index, post) {
    var url = placeholder.replace(123, post.id).replace('demo-slug', post.slug);

    newPosts += '[...]'
             +  '<a href="' + url + '" class="btn btn-primary text-white">More</a>'
             +  '[...]';
});

Which values you use as placeholders depends on what your route looks like and which validations are used (if any). Just make sure you use a placeholder text that is not already part of your URI.

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