Concatenate Javascript variable inside laravel blade curly braces
Asked Answered
T

3

7

I want to concatenate javascript variable within blade {{ curly braces }} as following:

Currently:

ajax: "{{ route(api.colors) }},"

What I want:

var page='colors';
...
ajax: "{{ route(api."+page+") }},"

Is it possible?

Turnbow answered 7/11, 2017 at 12:59 Comment(3)
You can do something like assign a data attribute to one of your HTML elements or a hidden HTML element where you pass the route (unless it contains sensitive information). And then access it in your javascript as a string.Decuple
I do have hidden input, but I want to pass its value dynamically.Turnbow
Does the route that you are passing depend on user interaction?Decuple
T
11

You cannot do this directly because the curly brackets are rendered on the server and javascript runs on the client side. You could put a placeholder in you route and then replace this part in your javascript code. Like so:

// Imagine the `api.page` route value is `/controller/{page}`:
ajax: "{{ route(api.page) }}".replace("{page}", page);
Tarver answered 7/11, 2017 at 13:6 Comment(5)
That is a very clever way to do it. +1Decuple
OK, I tried this ajax: "{{ route('api.items') }}".replace("{items}", 'colors') but it's not working, still pointing to old route.Turnbow
but does your rendered route contain a string {items}?Tarver
@Tarver Yes, it contains {items}.Turnbow
Clear and clever way to do it. There's no doubt. Great, man!Signal
T
0

You can try this code, it worked for me.

 var id = $('#user_id').val();
 console.log(id);   
 ajax: "{{ URL::to('/meme') }}/poster/"+id+"",
Teocalli answered 3/9, 2020 at 8:7 Comment(0)
W
0

You can use the ziggy library.

It has a helper function route(route_name) that you can easily use for this purpose.

Wharfinger answered 17/1, 2021 at 14:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.