How do I output unescaped HTML with javascript in Laravel Blade? - javascript

I have a VUEX store and a blog post that I need to output.
I use CKEditor for the input but I can't output the raw HTML with the #{{ }} in the front-end.
I have already tried to use #{{!! !!}} but apparently these doesn't work together.
This is the line that I output:
<div>#{{ $store.state.item.conteudo }}</div>
And this is the actual output of the code:
<p><strong>Teste Laravel</strong></p>

You're using double bracket so, You should try {!! !!} instead of {{!! !!}}.
So now your variable looks like.
{!! $text !!}
Check more info. displaying data

you can also do like this by using getter in your model
Hope it help!
public function getConteudoAttribute($value) {
return html_entity_decode($value);
}

Related

how to access the data sent from server(using flask), in javascript code?

from my server I sent a data like this to my front end,
return render_template("home.html", username=username)
I can access this data in the HTML using {{ username }}
But if I want to use this in javascript code(in script tags) how would I do that?
In order to use the data fetched from a Flask server in script tags, you have to convert the object into JSON representation which you can easily do by using Flask's tojson() template filter. For more info about tojson() visit this link.
Solution to your problem -
<script>
var username = JSON.parse('{{ username | tojson | safe}}');
//you can now use it in whichever way you want to
</script>
Hope this works for you.

Laravel: how to use laravel blade inside javascript?

Let's say i have data coming from my controller through Javascript.
So the data is paginated and i want display pagination result inside the javascript. I mean...I want to use the links() method inside javascript.
Controller
$schedules= DB::table('schedules')
->paginate(4);
Javascript,
success:function(schedules)
{
console.log(schedules);
$('#table').append(' <ul class="pager">'+{{ $schedules>links() }}+'</ul>');
})
But unfortunately not working, any help guys?
Push html paginate results from the controller, Enter the javascript code in the blade file, maybe
//controller
$paginate = '';
$paginate .= $datas->links();
//JS code in the blade file
<script type="text/javascript">
let paginate = '<div>';
paginate += {!! json_encode($paginate) !!}
paginate += '</div>'
consolelog(paginate)
</script>
You have an error in your blade syntax {{ }}:
$('#table').append(' <ul class="pager">'+{{ + $schedules>links() }}+'</ul>');
Remove the extra plus + icon before + $schedules>links() like so:
$('#table').append(' <ul class="pager">'+{{ $schedules>links() }}+'</ul>');
I think you can just convert the collection to a JSON.
Try this one:
Controller
$schedules= DB::table('schedules')
->paginate(4)->toArray();
return response()->json($schedules);
Javascript Ajax
success:function(schedules)
{
console.log(schedules);
$('#table').append(' <ul class="pager">'+schedules.links+'</ul>');
})
But in what I see, you're using the schedules also on your blade. In that case you can have a different function called for the ajax in your controller and different route.
Hope it helps!

Pass variables from controller to javascript function in Fat-Free Framework

I have some values on my controller that I want to pass to a javascript function in the view page.
In the controller, I have:
$f3->set('value', $value);
I can access the value on the view with {{#value}}, but how do I use(access) that value inside a javascript function on the view page??
<script type="text/javascript">
var value = XXX; //XXX in the {{#value}}, how do i access it in here???
</script>
It depends on the content stored inside $value.
If it's a basic string with no single/double quote inside, then the following code will work:
<script>
var value='{{ #value }}';
</script>
If it's an integer, the following code will work:
<script>
var value={{ #value }};
</script>
... although your IDE will probably report a syntax error.
If it's a float, the following code will work:
<script>
var value={{ str_replace(',', '.', #value) }};
</script>
... and your IDE will also probably report a syntax error. NB: the str_replace is for non-English locales that have decimal separator set to comma.
For all the rest (strings including quotes or arrays), you should convert your data to JSON, using one of the following techniques:
Technique 1:
Convert data to JSON and dump it to a JS object.
// controller.php (JSON encode)
$f3->set('data',json_encode($data));
<!-- template.html -->
<script>
var data={{ #data | raw }};
</script>
Pros: easy to use.
Cons: your IDE will report a syntax error + extra call to raw.
Technique 2:
Convert data to JSON, dump it to a JS string and parse it.
// controller.php (JSON encode + escape double quotes)
$f3->set('data',str_replace('\\u0022','\\\\u0022',
json_encode($data,JSON_HEX_APOS|JSON_HEX_QUOT)));
<!-- template.html -->
<script>
var data=JSON.parse('{{ #data | raw }}');
</script>
Cons: less easy to use + extra call to raw.
Pros: your IDE will not report any syntax error.
Technique 2bis:
Embed technique 2 in a F3 template filter.
// index.php
$tpl=Template::instance();
$tpl->filter('safejson',function($data){
$raw=\View::instance()->raw($data);
return str_replace('\\u0022','\\\\u0022',
json_encode($raw,JSON_HEX_APOS|JSON_HEX_QUOT));
});
<!-- template.html -->
<script>
var data=JSON.parse('{{ #data | safejson }}');
</script>
Pros: easy to use + your IDE will not report any syntax error.
Cons: extra call to raw.
Technique 3:
Convert data to JSON and embed it inside a DOM data- attribute.
// controller.php (JSON encode)
$f3->set('data',json_encode($data));
<!-- template.html -->
<div id="foo" data-json="{{ #data }}"></div>
<script>
var data=JSON.parse(document.getElementById('foo').dataset.json);
</script>
Pros: easy to use + your IDE will not report any syntax error + no extra call to raw.
I went a bit lazier than that.
I have my data in a dictionary file (F3). I load it in an input field at the bottom of my page and assign value via templating. I use Jquery (plain JS could be used to) to retrieve value.
Ex:
Dict data
'prf_conf'=>' Update your profile'
In my profile.html
`< input type = 'hidden' id ='prf_conf' value='{{#prf_conf}}' >`
//this loads data in whatever language on my page
JS
Confirm button text: (i used jquery-confirm.min.js in this example)
$.confirm({ title: $('#prf_conf').value()
… bit of gymnastic but worked well. No IDE issue…

How to use content with HTML inside JSON data with nunjucks and gulp-data?

how to use HTML with JSON with Gulp-data ? I'm using it in a static website building process with Gulp, Nunjucks and MJML
JSON
{
message:"Welcome to <span class='red'>world</span>"
}
.nunjucks file
{{ message }}
is giving this output in final HTML output
Welcome to <span class='red'>world</span>
Looks like Nunjucks uses autoescaping: true by default (due to their docs).
gulp-nunjucks-render uses envOptions to configure template engine (line 20 of its code).
You can try to pass autoescaping: false in options in gulp to disable escaping (more info in readme).
Or you can just use {{ message | safe }} in your template to disable escaping for one piece of code. Mode info in API Docs: Autoescaping

get current user in Javascript/jQuery Laravel 5.1

How I can get the current user in JS/Jquery? In the blade we can do like
{{Auth::user()}} But it wont work in the .js file.
As per looking at the standard and the way most javascript templates engine work, I would prefer to do something like this:
Install laracasts/utilities by using composer require laracasts/utilities
In the controller method, from where you are returning view, I would make it look like this:
public function returnUser(){
$user = Auth::user();
Javascript::put([ 'user.name' => $user->name, 'email' => $user->email ]);
return view('my.user.js');
}
In the blade file, I would simply do,
<script>alert("Hi " + user.name + ". Your email is " + user.email)</script>
And yeah, I would even prefer the way, #Robbin said. And yeah just one more edit to his answer, in laravel 5.1, Auth::user() should not be used. It should be used as auth()->user() //->name or ->email or ->anything.
You have to build an API and get it with AJAX. You cannot use blade in javascript files.
Or, in the <head> of your template, you place.
<script>
var user = {!! json_encode((array)auth()->user()) !!};
</script>
<!-- include your js file here-->
And use the user var in your js file.
EDIT:
As per Mark's comment this is indeed cleaner:
<script>
var user = {!! auth()->user()->toJson() !!};
</script>
<!-- include your js file here-->
simply =>
add any input or any tag to inject auth-user inside it, in my case:
< meta name="auth-check" content="{{ (Auth::check()) ? 'true' : 'false' }}">
in JS file u can get a value from your tag using jquery!
var authcheck = $('meta[name="auth-check"]').attr('content');
I hope my idea is useful, my best wishes

Categories