Display code snippet in Laravel blade - javascript

i need to display as text on the screen a snippet that contains some php variables, but when i load the page Laravel resolve this variables and give me a undefined variable error. Basically i need that when i try to display the snippet inside <code></code> tags it print something like this:
<script type='text/javascript>
var variable = '<?= $variable ?>';
</script>
I have tried already with {{htmlspecialchars}} but not work

In your controller you can assign the code to a variable :
$var = Blade::compileString('<script type=\'text/javascript\'>
var variable = \'<?= $variable ?>\';
</script>');
In your blade, access the variable as :
{{ $var }}

You can use highlight_string($code) to show the snippet. Inspiration from this post: How do I display PHP code in HTML?

Maybe you could try to enclose your snippet on a #verbatim block. This should escape its content of the rendering.
See more here: https://laravel.com/docs/5.5/blade#displaying-data

Related

Onclick in html-code vs find by id | How add value from php to js

I have two questions:
1)- What example is better- when i use onclick in html or when i find the element by in the script?
2)- Is it correct to pass $id value by \<\?=$id\?> in the second example?
<p onclick="message(<?=$id;?>)">Test</p>
<script>
function message(id){
alert(id);
}
</script>
or
<p id="message">Test</p>
<script>
$("#message").click(function(){
alert(<?=$id;?>); //<---id
}
</script>
Your first sample is an outright syntax error. You'd be generating
<p onclick="message-7">Test</p>
Since anything inside the " for the onclick is Javascript code, you're doing "undefined variable minus 7".
If you want to store your 7, you either assign it to a JS variable, or pass it as a function argument:
<script>
var foo = <?php echo json_encode($id); ?>;
</script>
<!-- or you do -->
<p onclick="somefunction(<?php echo json_encode($id); ?>);">click me</p>
Note the use of json_encode(). It is not necessary in this case, but it's a good habit to get into. You should never be directly dumping a PHP variable into a javascript context with out it. Remember that the client browser will never see your PHP code. It'll just see whatever javascript you're generating, and if the PHP value contains illegal javascript, you'll just be producing a javascript syntax error and killing the entire block.
Question 1 is a duplicate of addEventListener vs onclick
Question 2: Yes, that should work :-)

Interpret variable in Javascript file Laravel

I need to include a js file in my views.
But in this js file i need to interpret somes PHP variable.
Actually i do this :
#section('javascript')
<script>
alert("{{{test}}}");
</script>
#stop
But i REALLY need to do this :
#section('javascript')
{!! Html::script('js/test.js') !!}
#stop
test.js :
alert("{{{test}}}");
I need to declare a lot o variable. So my JS file will be very huge. And i don't want to show this directly in the source code.
How can i do ?
Thank you !
You can only pass the variable to the javascript like so:
#section('javascript')
<script>
var test = {{{$test}}};
</script>
#stop
then in your javascript file included at the bottom you can use it:
alert(test);
Let me just mention that this is not a great way of handling the passing variables from php to javascript.
When I need to do something like this, I usually create a meta tag on the page which would contain the alert information.
<meta name="someAlertValue" content="{{{ $test }}}" />
Then you can very easily grab that via jQuery.
var alert_text = $('meta[name=someAlertValue]').attr('content');
I find this approach to be much cleaner and maintainable than trying to drop php variables directly into your javascript.
I had the same problem, and wanted to have a stand alone js which will have bunch of variables taken from config() or even from database, multi-language, and will be configurable, or even will work with query parameters.
Maybe it's a hard way, but i've created a route:
Route::get('/js-modules/test.js',function(){ return view('js-modules.test');})->name('my_js);
So in the view resources/views/js-modules/test.blade.php you can put your js code together with your PHP stuff.
Or you can route it to a controller and have even more background work. it looks a bit slow (in the browser) on the first run , but second request it'll be cashed and retrieved as the regular js file
And now you can link it to any of your pages with
<script src="{{route('my_js')}}"></script>

Smarty - can't insert variable content into javascript

I need to insert content of variable with Smarty syntax into javascript, like below. The script is checking if page is opened from validation link in email sent to customer.
{literal}
<script>
if ((document.URL).indexOf("validation") > -1) {
$('.loginForm').append(
"<p class='middleWarningTextP loginMessage'>{/literal}{$VALIDATION_NOTICE->getMessage()}{literal}</p>");
}
</script>
{/literal}
Problem is, that this works only if javascript condition is true, otherwise page is loaded wrong: between <header> and </header> tag is nothing! and therefore css style is not loaded. I don't understand it, is there a way to repair it?
You should remove the {literal} tags. Smarty does not execute statements within these tags More info. But then, if use curly braces inside your javascript, you need to write your statements on multiple lines:
var test = {
value: 'test'
}
If you're using Smarty 3
<script>
if ((document.URL).indexOf("validation") > -1) {
$('.loginForm').append(
"<p class='middleWarningTextP loginMessage'>{$VALIDATION_NOTICE->getMessage()}{literal}</p>");
}
</script>
That is, simply remove the {literal} tags
If you're using Smarty 2 instead, i think it's something like this
<script>
if ((document.URL).indexOf("validation") > -1) {ldelim}
$('.loginForm').append(
"<p class='middleWarningTextP loginMessage'>{$VALIDATION_NOTICE->getMessage()}</p>");
{rdelim}
</script>
Problem was not with {literals} tags or syntax. Problem was that $VALIDATION_NOTICE->getMessage() variable was not set in some cases. Therefore I added this condition:
{if !is_array($VALIDATION_NOTICE) and $VALIDATION_NOTICE}{$VALIDATION_NOTICE->getMessage()}{/if}
and now it works right.

Tooltips in Joomla containing HTML

I created a component using Component Creator for Joomla 3.X
The problem is that on the site the tooltips show html code. For example:
<strong>Title</strong><br/>Description
Instead, on the administrator they are displayed properly:
Title
Description
I was reviewing the documentation here and here, and it seems that it is possible to define the output format when calling the tooltip function but there are no calls inside the component to that function. The only call I see is JHtml::_('behavior.tooltip'); at the begining of the view file and don't know how to specify the output format.
The site is in this URL:
http://50.87.185.99/colombianadederecho_blank/index.php/administradores-ph/registrarse
Added:
It seems like the code is called when building the label for each field:
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('document'); ?></div>
<div class="controls"><?php echo $this->form->getInput('document'); ?></div>
</div>
And it is stored in the title attribute:
title="<strong>Title</strong><br />Description"
So, I think the problem is in the Javascript function, maybe using a .text() jQuery function instead of a .html().
Inspecting the source code I found this, but don't understand why it is not working properly:
window.addEvent('domready', function() {
$$('.hasTip').each(function(el) {
var title = el.get('title');
if (title) {
var parts = title.split('::', 2);
el.store('tip:title', parts[0]);
el.store('tip:text', parts[1]);
}
});
var JTooltips = new Tips($$('.hasTip'), {"maxTitleChars": 50,"fixed": false});
});
jQuery(document).ready(function() {
jQuery('.hasTooltip').tooltip({"html": true,"container": "body"});
});
Solution:
As #ilias found it was a problem between libraries. I had to disable the bootstrap call in the header using this plugin and call it from the end of the body:
<script src="/site/media/jui/js/bootstrap.min.js" type="text/javascript"></script>
I don't know the code that Component Creator produces, however I assume that the tooltips are like in the administrator views. If this is the case you should check for something like this:
<button type="submit" class="btn hasTooltip" title="<?php echo JHtml::tooltipText('JSEARCH_FILTER_SUBMIT'); ?>"><i class="icon-search"></i></button>
and enclose the contents of JHtml::tootlipText() in strip_tags().
Otherwise try to find the line <strong>Title</strong><br/>Description where the tags are shown and enclose it in strip_tags(). For example you might have something that looks like:
echo $this->escape($item->description);
that should be turned into:
echo $this->escape(strip_tags($item->description));

Dynamically creating jQuery listview in PHP loop

I would like to populate a jQuery listview in a PHP loop, and I attempted to do so by echoing javascript code that populates the list with a PHP variable. This is what I'm working with:
My HTML
<div data-role='page' id='feedPage'>
<div data-role='content'>
<ul id='pics' data-role='listview'>
<li>test</li>
</ul>
</div>
</div>
and my PHP / JavaScript
echo "<script type='javascript'>
var pics = \$('#pics')
var pitem = \$('<li/>').html($myArray[element])
var plink = \$('<a/>')
pitem.append(plink)
pics.append(pitem)
pics.listview('refresh')
</script>";
but the list comes up blank. This code is running inside of a PHP for loop, and I am able to access and manipulate all the elements of $myArray just fine in PHP, but I cannot seem to populate the list. I even tried running this code with a simple .html('hello') to no avail. All I get is a blank list with the exception of the test item I hardcoded in the HTML. Is there a way to generate a list in PHP like this, and if so, how can I do it properly?
Thanks!
SOLUTION:
I got this working simply by doing <script type='text/javascript'> and .html('$myArray[element]') (notice the single quotes). This works because the javascript is running inside a PHP echo. Oh, and none of my $ needed to be escaped. Final code:
echo "<script type='text/javascript'>
var pics = $('#pics')
var pitem = $('<li/>').html('$myArray[element]')
var plink = $('<a/>')
pitem.append(plink)
pics.append(pitem)
pics.listview('refresh')
</script>";
I think the main problem is in type='javascript', it should be type='text/javascript'.
Another thing to consider is that the content of the $myArray[element] needs to be printed as a javascript string. Running $myArray = array_map('json_encode', $myArray); should do the trick.
You forgot to put your JS-code into document.ready event callback
$(document).ready(function($){
var pics = $('#pics')
var pitem = $('<li/>').html($myArray[element])
var plink = $('<a/>')
pitem.append(plink)
pics.append(pitem)
pics.listview('refresh')
});

Categories

Resources