Comments in blade #php directive - laravel-5.4

I am learning laravel 5.4. And I have a question. If I want to add comments in blade template engine's #php directive area, such as
#php
$a = 1;
$b = 1;
#endphp
Is it just like normal php code :
#php
//$a = 1;
$b = 1;
#endphp
Is this right?

{{-- this is default blade comment --}}

Related

Laravel nested select and conditional statement in view blade

So I've succeeded to make a calendar display for the current month. This time, I want to show event details for a specific date. I'm not sure how to get the $event data where $event == $date.
This is the controller. I have event and dates to be used in the view:
$event = Event::where("started_at", '>=', Carbon::now()->subDays(30)->toDateTimeString())
->orderBy("started_at", "asc")
->first();
$data["event"] = $event;
$data["month"] = Carbon::now()->month;
$data["dates"] = range('1', date('t'));
return view('event.all', $data);
This is the event.all view:
#foreach($dates as $date)
<div class="seven-cols">
<div class="titlehead">
<h6>{{$date}}</h6>
<h6 style="color: lightgrey;">{{date("D", mktime(0, 0, 0, $month, $date))}}</h6>
<div style=" ">{{$eventdate = date('d',strtotime(#$event->started_at))}}</div>
#if($event->started_at == $date)
<div>Test</div>
#endif
</div>
</div>
#endforeach
What I got for this code:
As this other answer suggests I would use CarbonPeriod (or create a range with a loop if CarbonPeriod not available for you) and then collect the events for each date at the same time.
As a good practice, we should avoid keeping too much logic inside the templates and therefore build as much as we can of the content before actually building the template itself.
Using your example, and assuming that you only want to show one event for each day we could have something like this:
(Not tested code though)
$startDate = Carbon::now()->subDays(30)->toDateTimeString();
$endDate = Carbon::now()->toDateTimeString();
// Narrow down the list from the database
$events = Event::whereBetween("started_at", [$startDate, $endDate])
->orderBy("started_at")
->get();
$data = CarbonPeriod::create(
$startDate,
$endDate
)
->map(function(Carbon $date) {
$event = $events
->where("started_at", $date->toDateTimeString())
->first();
return [
"date" => $date,
"event" => $event,
];
});
return view('event.all', $data);
And in the template:
#foreach($data as $day)
<div class="seven-cols">
<div class="titlehead">
<h6>{{$day["date"]->day}}</h6>
<h6 style="color: lightgrey;">{{$day["date"]->format("D")}}</h6>
<div style=" ">{{$day["date"]->format("d")}}</div>
#if(!is_null($day["event"]))
<div>{{$day["event"]->someTextField}}</div>
#endif
</div>
</div>
</div>
#endforeach
I hope it helps!

Laravel - Foreach value in php tags with blade template

I have trouble with that, let me explain.
In controller, I get users.
$users = User::where('steamid','!=','')->orderBy('time','DESC')->get();
After that in Blade template I need to use PHP function for the get steam profile link from steam id.
I have a function:
function SteamName($steamid){
$xml = simplexml_load_file("http://steamcommunity.com/profiles/$steamid/?xml=1");//link to user xmla
$username = $xml->steamID;
return $username;
}
I have a foreach for every user:
#foreach($users as $user)
//so, i need to do like this;
<?php print SteamName($user->steamid) ?>
#endforeach
Put your function inside User Model
function SteamName($steamid){
$xml = simplexml_load_file("http://steamcommunity.com/profiles/$steamid/?xml=1");//link to user xmla
$username = $xml->steamID;
return $username;
}
From Your blade call the function :
#foreach($users as $user)
{{ $user->SteamName($user->steamid) }}
#endforeach
You can also try this
#foreach ($users as $user)
{{$user->steamid}}
#endforeach

How to add valueless attribute to <form> tag using yii2 ActiveForm

How do I add a value-ess attribute to the form tag?
I want to have:
<form data-abide >
according to: http://foundation.zurb.com/sites/docs/abide.html
I've tried
<?php $form = ActiveForm::begin(['id' => 'contact-form', 'options'=>['data-abide'=>'']]); ?>
but get output:
<form data-abide="ak8hvf-abide" >
Try this:
'options'=>['data-abide'=>true]
Reference: In the framework helper BaseHtml.php file, find :
function renderTagAttributes
Where :
foreach ($attributes as $name => $value) {if (is_bool($value)) { if ($value) { $html .= " $name"; } } elseif...
...
elseif ($value !== null) { $html .= " $name=\"" . static::encode($value) . '"'; }
...
It is actually behaving as expected - turns out it is the adide.js which adds the extra security token:
https://github.com/yiisoft/yii2/issues/10532#issuecomment-169952232
Thanks everyone for help!
For me, both 'data-abide'=>'' and 'data-abide'=>true works fine...
Could it be something outdated? Can you try run a composer update in your project?

Twig and truncating text

I created this simple Twig page on localhost on MAMP:
<html>
<head>
<style type="text/css">
table {
border-collapse: collapse;
}
tr.heading {
font-weight: bolder;
}
td {
border: 0.5px solid black;
padding: 0 0.5em;
}
</style>
</head>
<body>
<h2>Automobiles</h2>
<table>
<tr class="heading">
<td>Vehicle</td>
<td>Model</td>
<td>Price</td>
</tr>
{% for d in data %}
<tr>
<td>{{ d.manufacturer|escape }}</td>
<td>{{ d.model|escape }}</td>
<td>{{ d.modelinfo|raw }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
and this is the code behind it:
<?php
// include and register Twig auto-loader
include 'Twig/Autoloader.php';
Twig_Autoloader::register();
// attempt a connection
try {
$dbh = new PDO('mysql:dbname=world;host=localhost', 'root', 'mypass');
} catch (PDOException $e) {
echo "Error: Could not connect. " . $e->getMessage();
}
// set error mode
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// attempt some queries
try {
// execute SELECT query
// store each row as an object
$sql = "SELECT manufacturer, model, price FROM automobiles";
$sth = $dbh->query($sql);
while ($row = $sth->fetchObject()) {
$data[] = $row;
}
// close connection, clean up
unset($dbh);
// define template directory location
$loader = new Twig_Loader_Filesystem('templates');
// initialize Twig environment
$twig = new Twig_Environment($loader);
// load template
$template = $twig->loadTemplate('cars.html');
// set template variables
// render template
echo $template->render(array (
'data' => $data
));
} catch (Exception $e) {
die ('ERROR: ' . $e->getMessage());
}
?>
However, I am planning to truncate the text in the modelinfo field, I believe this can be done in MySQL with the select LEFT function, but how should I modify the query?
All help is appreciated!
You can truncate text in your Twig template like this:
{{ d.modelinfo[:10] }}
That should return the first 10 characters in d.modelinfo.
Take a look at the slice filter documentation page.
Twig has a truncate filter but you have to enable the text extensions by adding the following to your config.yml file.
services:
twig.extension.text:
class: Twig_Extensions_Extension_Text
tags:
- { name: twig.extension }
Then in your template you can use the truncate filter and pass it an integer which denotes the length of the truncation.
{{ d.modelinfo|truncate(50) }}

Twig framework and datetime errors

I'm running an events site - powered by PHP/MySQL, on Apache 2.28.
I can get the HTML table to display as per http://devzone.zend.com/article/13633.
For this site on localhost, I'm using the Twig framework mentioned at www. twig-project. org
The content is extracted from a local MySQL database:
My code:
<html>
<head>
<style type="text/css">
table {
border-collapse: collapse;
}
tr.heading {
font-weight: bolder;
}
td {
border: 1px solid black;
padding: 0 0.5em;
}
</style>
</head>
<body>
<h2>Events</h2>
<table>
<tr class="heading">
<td>Event time</td>
<td>Event name</td>
</tr>
{% for d in data %}
<tr>
<td>{{ d.evtime|escape }}</td>
<td>{{ d.evname|escape }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
// The PHP file is below
<?php
// include and register Twig auto-loader
include 'Twig/Autoloader.php';
Twig_Autoloader::register();
// attempt a connection
try {
$dbh = new PDO('mysql:dbname=world;host=localhost', 'root', 'MYPASS');
} catch (PDOException $e) {
echo "Error: Could not connect. " . $e->getMessage();
}
// set error mode
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// attempt some queries
try {
// execute SELECT query
// store each row as an object
$sql = "SELECT * FROM myeventdb";
$sth = $dbh->query($sql);
while ($row = $sth->fetchObject()) {
$data[] = $row;
}
// close connection, clean up
unset($dbh);
// define template directory location
$loader = new Twig_Loader_Filesystem('templates');
// initialize Twig environment
$twig = new Twig_Environment($loader);
// load template
$template = $twig->loadTemplate('countries.tmpl');
// set template variables
// render template
echo $template->render(array (
'data' => $data
));
} catch (Exception $e) {
die ('ERROR: ' . $e->getMessage());
}
?>
However, I can't get the datetime to display as this for my events:
1:30pm Geography Class
Instead it displays as
13:30:00 Geography Class
Why is this, and what do I need to fix it, within the Twig syntax?
I'm fairly new to this, and I had a look through the documentation but there wasn't much on the site about it.
Cheers.
So the script is displaying 13:30:00 because that's what's coming out of the database - you're not formatting the date anywhere.
In your Twig template, you can use a date filter to format the date to your liking, according to the PHP date function formatting:
{{ d.evtime|date('g:ia')|escape }}
If you wanted to do the formatting beforehand, just use a combination of date and strtotime:
$formatted_time = date('g:ia',strtotime($unformatted_time));