Skip to content
Snippets Groups Projects
InlineLanguageLabelsViewHelper.php 2.66 KiB
<?php

namespace SGalinski\SgMail\ViewHelpers;

/***************************************************************
 *  Copyright notice
 *
 *  (c) sgalinski Internet Services (https://www.sgalinski.de)
 *
 *  All rights reserved
 *
 *  This script is part of the SG project. The SG project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/

use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;

/**
 * View helper to render language labels to
 * json array to be used in js applications.
 *
 * Renders to SG.lang.'extension name' object
 *
 * Example:
 * {namespace rs=SGalinski\RsEvents\ViewHelpers}
 * <rs:inlineLanguageLabels labels="label01,label02" />
 */
class InlineLanguageLabelsViewHelper extends AbstractViewHelper {

	/**
	 * Register the ViewHelper arguments
	 */
	public function initializeArguments() {
		parent::initializeArguments();
		$this->registerArgument('labels', 'string', 'Comma separated list of label keys to include', FALSE, '');
		$this->registerArgument('htmlEscape', 'bool', 'Escape the HTML output', FALSE, FALSE);
	}

	/**
	 * Renders the required javascript to make the language labels available
	 *
	 * @return string
	 */
	public function render() {
		$labels = $this->arguments['labels'];
		$htmlEscape = $this->arguments['htmlEscape'];
		$extensionName = $this->renderingContext->getControllerContext()->getRequest()->getControllerExtensionName();
		$labels = GeneralUtility::trimExplode(',', $labels, TRUE);
		$languageArray = [];
		foreach ($labels as $key) {
			$value = LocalizationUtility::translate($key, $extensionName);
			$languageArray[$key] = ($htmlEscape ? htmlentities($value) : $value);
		}
		return '
			<script type="text/javascript">
			var SG = SG || {};
			SG.lang = SG.lang || {};
			SG.lang.' . $extensionName . ' = SG.lang.' . $extensionName . ' || {};
			var languageLabels = ' . json_encode($languageArray) . ';
			for (label in languageLabels) {
				SG.lang.' . $extensionName . '[label] = languageLabels[label];
			}
			</script>
		';
	}
}