How do I get the current language inside a controller?
I already tried this:
return function ($kirby, $site) {
$language = $kirby->language();
[...]
}
but it returns the error:
Undefined variable: language
I’m trying to send language specific mails and that seems to be the best approach. I’m open to any other solutions if that’s not a viable option.
Where is the error thrown? Are you passing the variable to the template? Since you are defining the variable in your controller, it can’t possibly be undefined unless you don’t pass it to the template or wherever you are then using that variable.
Welcome to the Kirby forum!
1 Like
I changed my variable name from $language to $currentlanguage to prevent any confusion, because it still throws the same error:
Undefined variable: language
Here’s a kind of cleaned up version of my script:
<?php
return function ($kirby, $site) {
$alert = null;
$data = null;
if ($kirby->request()->is('POST') && get('submit')) {
$servername = "localhost";
$username = "USERNAME";
$password = "PASSWORD";
$dbname = "DBNAME";
$tablename = "signups";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
$alert['error'] = "Verbindungsfehler (ERR01)";
} else {
$sql = "INSERT INTO $tablename (email) VALUES ('" . $_POST["email"] . "')";
}
if ($conn->query($sql) === TRUE) {
$conn->close();
// Set mail content
$currentlanguage = $kirby->language();
$mail_heading = $site->page('mails')->content($currentlanguage)->mail_confirm_heading();
$mail_text = $site->page('mails')->content($currentlanguage)->mail_confirm_text();
$mail_btn = $site->page('mails')->content($currentlanguage)->mail_confirm_btn();
$mail_url = $currentlanguage;
try {
$kirby->email([
'template' => 'signup-confirmation-request',
'from' => 'noreply@mysiteapp.com',
'to' => $data['email'],
'subject' => 'mysite - Email confirmation',
'data' => [
'mail_heading' => $mail_heading,
'mail_text' => $mail_text,
'mail_btn' => $mail_btn,
'mail_url' => $mail_url,
]
]);
} catch (Exception $error) {
// The error I'm getting
$alert['error'] = $error->getMessage();
}
// forward to success page
if (empty($alert) === true) {
header("Location: /signup-success");
die();
}
} else {
$alert['error'] = "Verbindungsfehler (ERR02)";
}
}
return [
'alert' => $alert,
'data' => $data,
'success' => $success ?? false
];
};
That’s a bit weird, sure you are not using $language
anywhere? Could you post a screenshot of the whoops error message including stack trace?
Apart from that, $kirby->language()
returns the language objects, so to get the content in the correct language, you have to pass the language code, not the object.
$site->page('mails')->content($currentlanguage->code())->mail_confirm_heading();
Oops. Sorry, my bad. I totally forgot, that I already had the language variable in my mail templates