From 6e6d80c044a81b6107ef7410733946a1b6cf0a51 Mon Sep 17 00:00:00 2001 From: Daniel Rudolf Date: Thu, 29 Aug 2019 23:10:35 +0200 Subject: [PATCH] Add Pico::substituteUrl() and `url` Twig filter Allows theme developers and users to use URL placeholders like `%base_url%` in meta headers, e.g. to include images. --- lib/Pico.php | 30 ++++++++++++++++++++++++++++++ lib/PicoTwigExtension.php | 3 ++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/lib/Pico.php b/lib/Pico.php index 48d243b..fcb9170 100644 --- a/lib/Pico.php +++ b/lib/Pico.php @@ -2240,6 +2240,36 @@ class Pico return substr($path, $contentDirLength, -$contentExtLength) ?: null; } + /** + * Substitutes URL placeholders (e.g. %base_url%) + * + * This method is registered as the `url` Twig filter and often used to + * allow users to specify absolute URLs in meta data utilizing the known + * URL placeholders `%base_url%`, `%plugins_url%`, `%themes_url%`, + * `%assets_url%` and `%theme_url%`. + * + * Don't confuse this with the `link` Twig filter, which takes a page ID as + * parameter. However, you can indeed use this method to create page URLs, + * e.g. `{{ "%base_url%?sub/page"|url }}`. + * + * @param string $url URL with placeholders + * + * @return string URL with replaced placeholders + */ + public function substituteUrl($url) + { + $variables = array( + '%base_url%?' => $this->getBaseUrl() . (!$this->isUrlRewritingEnabled() ? '?' : ''), + '%base_url%' => rtrim($this->getBaseUrl(), '/'), + '%plugins_url%' => rtrim($this->getConfig('plugins_url'), '/'), + '%themes_url%' => rtrim($this->getConfig('themes_url'), '/'), + '%assets_url%' => rtrim($this->getConfig('assets_url'), '/'), + '%theme_url%' => $this->getConfig('themes_url') . $this->getTheme() + ); + + return str_replace(array_keys($variables), $variables, $url); + } + /** * Returns the URL of the themes folder of this Pico instance * diff --git a/lib/PicoTwigExtension.php b/lib/PicoTwigExtension.php index a774184..bfe01fe 100644 --- a/lib/PicoTwigExtension.php +++ b/lib/PicoTwigExtension.php @@ -75,7 +75,8 @@ class PicoTwigExtension extends Twig_Extension 'markdown' => new Twig_SimpleFilter('markdown', array($this, 'markdownFilter')), 'map' => new Twig_SimpleFilter('map', array($this, 'mapFilter')), 'sort_by' => new Twig_SimpleFilter('sort_by', array($this, 'sortByFilter')), - 'link' => new Twig_SimpleFilter('link', array($this->pico, 'getPageUrl')) + 'link' => new Twig_SimpleFilter('link', array($this->pico, 'getPageUrl')), + 'url' => new Twig_SimpleFilter('url', array($this->pico, 'substituteUrl')) ); }