Helpers
Masonite has several helpers available. Many helpers are used internally to help write clean Masonite code but can be used in your projects as well.

Url

The Url helper allows you to create a full path URL:
1
from masonite.helpers import url
2
3
url.url("/dashboard") #== example.com/dashboard
Copied!
The URL will come from the APP_URL in your application config file.
You can also generate a URL for an asset:
1
url.asset("s3.invoices", "invoice-01-2021.pdf")
Copied!
You can also generate a URL for a route by its route name:
1
url.route("users.profile", {"id": 1}) #== http://masonite.app/users/1/profile/
Copied!
You can also generate just a path:
1
url.route("users.profile", {"id": 1}, absolute=False) #== /users/1/profile/
Copied!

Compact

The compact helper is a shortcut helper when you want to compile a dictionary from variables.
There are times when you will have instances like this:
1
from masonite.view import View
2
3
def show(self, view: View):
4
users = User.all()
5
articles = Article.all()
6
return view.render('some.view', {"users": users, "articles": articles})
Copied!
Notice we repeated the users and articles key the same as the variables name. In this case we can use the compact helper to clean the code up a bit:
1
from masonite.view import View
2
from masonite.helpers import compact
3
4
def show(self, view: View):
5
users = User.all()
6
articles = Article.all()
7
return view.render('some.view', compact(users, articles))
Copied!

Optional

The optional helper takes an object and allows any method calls on the object. If the method exists on the object it will return the value or else it will return None:
You may have a peice of code that looks like this:
1
if request.user() and request.user().admin == 1:
2
#.. do something
Copied!
with the optional helper you can condense the code into something like this:
1
from masonite.helpers import optional
2
3
if optional(request.user()).admin == 1:
4
#.. do something
Copied!

Configuration

You can easily get configuration values using dot notation:
To get the application key for example:
1
from masonite.configuration import config
2
3
key = config("application.key")
Copied!
Event more convenient is the ability to use dot notation even inside a dictionary inside a configuration file.
Assuming you have a dictionary set inside a configuration like this:
1
# config/appliation.py
2
3
HASHING = {
4
"default": "bcrypt",
5
"bcrypt": {"rounds": 10},
6
"argon2": {"memory": 1024, "threads": 2, "time": 2},
7
}
Copied!
You may use dot notation to get any value inside the HASHING constant like this:
1
from masonite.configuration import config
2
3
key = config("application.hashing.bcrypt.rounds") #== 10
Copied!
Last modified 2mo ago
Export as PDF
Copy link