Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add method to get route by language #3188

Draft
wants to merge 1 commit into
base: develop
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
52 changes: 51 additions & 1 deletion system/src/Grav/Common/Page/Page.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ class Page implements PageInterface
protected $url;
/** @var array */
protected $routes;
/** @var array */
protected $languageRoutes;
/** @var bool */
protected $routable;
/** @var int */
Expand Down Expand Up @@ -1905,6 +1907,54 @@ public function route($var = null)
return $this->route;
}

/**
* @param string|null $language
* @return string
*/
public function languageRoute(?string $language = null): string
{
if ($language === null || !array_key_exists($language, $this->translatedLanguages())) {
return $this->route();
}

if (!empty($this->languageRoutes[$language])) {
return $this->languageRoutes[$language];
}

$currentLanguage = trim(basename($this->extension, 'md'), '.') ?: null;

if ($language === $currentLanguage) {
return $this->route();
}

$excludeLanguage = false;
$defaultLanguage = Grav::instance()['language']->getDefault();

if ($language === $defaultLanguage) {
$includeDefaultLanguage = (bool)Grav::instance()['config']->get('system.languages.include_default_lang_file_extension');
$excludeLanguage = !$includeDefaultLanguage;
}

$path = sprintf('%1$s%2$s%3$s%2$s', $this->path, DS, $this->folder);
$name = str_replace(
sprintf('.%s.md', $currentLanguage),
$excludeLanguage ? '.md' : sprintf('.%s.md', $language),
$this->name
);

$filePath = sprintf('%s%s', $path, $name);

if (file_exists($filePath)) {
$page = new Page();
$page->parent(new Page());
$page->init(new \SplFileInfo($filePath));

return $page->route();
}

return $this->route();
}

/**
* Helper method to clear the route out so it regenerates next time you use it
*/
Expand Down Expand Up @@ -1986,7 +2036,7 @@ public function id($var = null)
{
if (null === $this->id) {
// We need to set unique id to avoid potential cache conflicts between pages.
$var = time() . md5($this->filePath());
$var = $var ?? time() . md5($this->filePath());
}
if ($var !== null) {
// store unique per language
Expand Down