langswitcher.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace Grav\Plugin;
  3. use Grav\Common\Language\LanguageCodes;
  4. use Grav\Common\Page\Page;
  5. use \Grav\Common\Plugin;
  6. class LangSwitcherPlugin extends Plugin
  7. {
  8. /**
  9. * @return array
  10. */
  11. public static function getSubscribedEvents()
  12. {
  13. return [
  14. 'onPluginsInitialized' => ['onPluginsInitialized', 0]
  15. ];
  16. }
  17. /**
  18. * Initialize configuration
  19. */
  20. public function onPluginsInitialized()
  21. {
  22. if ($this->isAdmin()) {
  23. $this->active = false;
  24. return;
  25. }
  26. $this->enable([
  27. 'onTwigInitialized' => ['onTwigInitialized', 0],
  28. 'onTwigTemplatePaths' => ['onTwigTemplatePaths', 0],
  29. 'onTwigSiteVariables' => ['onTwigSiteVariables', 0]
  30. ]);
  31. }
  32. /** Add the native_name function */
  33. public function onTwigInitialized()
  34. {
  35. $this->grav['twig']->twig()->addFunction(
  36. new \Twig_SimpleFunction('native_name', function($key) {
  37. return LanguageCodes::getNativeName($key);
  38. })
  39. );
  40. }
  41. /**
  42. * Add current directory to twig lookup paths.
  43. */
  44. public function onTwigTemplatePaths()
  45. {
  46. $this->grav['twig']->twig_paths[] = __DIR__ . '/templates';
  47. }
  48. /**
  49. * Set needed variables to display Langswitcher.
  50. */
  51. public function onTwigSiteVariables()
  52. {
  53. $data = new \stdClass;
  54. $page = $this->grav['page'];
  55. $data->page_route = $page->rawRoute();
  56. if ($page->home()) {
  57. $data->page_route = '/';
  58. }
  59. $languages = $this->grav['language']->getLanguages();
  60. $data->languages = $languages;
  61. if ($this->config->get('plugins.langswitcher.untranslated_pages_behavior') !== 'none') {
  62. $translated_pages = [];
  63. foreach ($languages as $language) {
  64. $translated_pages[$language] = null;
  65. $page_name_without_ext = substr($page->name(), 0, -(strlen($page->extension())));
  66. $translated_page_path = $page->path() . DS . $page_name_without_ext . '.' . $language . '.md';
  67. if (file_exists($translated_page_path)) {
  68. $translated_page = new Page();
  69. $translated_page->init(new \SplFileInfo($translated_page_path), $language . '.md');
  70. $translated_pages[$language] = $translated_page;
  71. }
  72. }
  73. $data->translated_pages = $translated_pages;
  74. }
  75. $data->current = $this->grav['language']->getLanguage();
  76. $this->grav['twig']->twig_vars['langswitcher'] = $data;
  77. if ($this->config->get('plugins.langswitcher.built_in_css')) {
  78. $this->grav['assets']->add('plugin://langswitcher/css/langswitcher.css');
  79. }
  80. }
  81. public function getNativeName($code) {
  82. }
  83. }