Views
Views in Yabasi are responsible for containing the HTML served by your application. They separate your controller and application logic from your presentation logic, promoting cleaner, more maintainable code.
Creating Views
Views are stored in the resources/views
directory. A simple view might look like this:
<html>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>
Returning Views from Controllers
You can return a view from your controller using the view()
helper method:
public function show($id)
{
$user = User::find($id);
return $this->view('user.profile', ['user' => $user]);
}
Passing Data to Views
You can pass data to views as an array. Here are various examples including sorting methods:
return $this->view('user.profile', [
'user' => User::find($id),
'latestArticles' => Content::latest()->get(), // Get articles ordered by created_at DESC
'oldestArticles' => Content::oldest()->get(), // Get articles ordered by created_at ASC
'popularArticles' => Content::orderByDesc('views')->get(), // Order by views DESC
'alphabeticalArticles' => Content::orderByAsc('title')->get(), // Order by title ASC
'customDateArticles' => Content::latest('published_at')->get(), // Order by specific column
'recentFive' => Content::latest()->limit(5)->get(), // Get latest 5 articles
'publishedArticles' => Content::where('status', '=', '1')
->latest()
->get() // Combine with where clause and order by latest
]);
Twig Templating Engine
Yabasi uses the Twig templating engine, which provides a powerful set of features for creating views:
Variables
{{ variable }}
{{ user.name }}
{{ user['name'] }}
Control Structures
{% if user %}
Hello, {{ user.name }}!
{% endif %}
{% for user in users %}
<li>{{ user.name }}</li>
{% endfor %}
Template Inheritance
Twig allows you to build a base "skeleton" template that contains all the common elements of your site:
<!-- layout.twig -->
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
<!-- child.twig -->
{% extends "layout.twig" %}
{% block title %}My Page{% endblock %}
{% block content %}
<h1>Welcome to my page!</h1>
{% endblock %}
Optimization
Yabasi can cache your views for faster rendering. To cache all your views, run:
php
yabasi
view:cache
To clear the view cache:
php
yabasi
view:clear