Multilingual PHP Inline Replacement in HTML ([en]...[/en] etc.) - php

I am a coding beginner and have my PHP/HTML web project in German. Now I want to make it available in English in the easiest way. I don't want to add other languages in the future, so I want to try it in the easiest (and maybe not the most proper) way.
I have PHP files with HTML content and the selected language available in a var, i.e.:
<?php
$lang = "en";
?>
<h1>Title in German</h1>
So all the German words are inline HTML. My idea was to create something like:
<h1>[de]Title in German[/de][en]Title in English[/en]</h1>
But I have no idea how to replace it on every load in a smart way. So it is more a topic on "live replacement".
Working with constants in an external language file is of course also an option, like all the other options to make a multilingual site I found on Stackoverflow.
But maybe there is a "quick and dirty" possibility option like the one I mentioned?
Thank you for every hint!

You could try and do this will almost only HTML and CSS. You would need to add this at the top of your page:
<?php
$pageLanguage = "en";
function getLanguageStyle($showLanguage)
{
global $pageLanguage;
$display = ($showLanguage == $pageLanguage ? 'inline' : 'none');
return " span.$showLanguage { display: $display }\n";
}
echo "<style>\n".
getLanguageStyle('en').
getLanguageStyle('de').
"</style>\n";
?>
It sets up a style for each language, which you can then use like this:
<h1><span class="de">Title in German</span><span class="en">Title in English</span></h1>
The advantage here is that you don't need to mix HTML and PHP. This is not a normal way of doing this, but it will work. On very complex pages, where these styles are applied after the first render, this might not be pleasant for your visitors.

Usually translations are made that way:
You have key to translation map for each language, then you request some function that takes proper map for that language and returns translation:
function translate(string $lang, string $key) {
/*
* This usually sits in some file in dir like `/src/i18n/en.json`
* And you do then `$translations = json_decode(require "/src/i18n/{$lang}.json")`
*/
$translations = [
'en' => [
'page.title' => 'Page Title',
...
],
'de' => [
'page.title' => 'Page Title In German',
...
],
];
return $translations[$lang][$key] ?? $key;
}
<h1><?= translate($lang, 'page.title'); ?></h1>

Related

Include problems with PHP

I need a little help! I'm making multilangual site with php and I got an issue. I want to include array into another array.
There is one php file
<?php
$lang = array(
'en' => array(
include ('translations/nav-translation/en.php');
),
'lv' => array(
include ('translations/nav-translation/lv.php');
),
);
?>
And php file that I want to include
<?php
"home" => "Home",
"blog" => "Blog",
"about" => "About me",
?>
If you don't want to use yaml it's better to return arrays from your lang files
en.php:
<?php
return ["home" => "Home",....]
?>
index.php:
<?php
$lang = array(
'en' => include("translations/nav-translation/en.php"),
'lv' => ....
Can't you just set up your include files like this:
translations/nav-translation/en.php
<?php
$lang['en'] = array(
"home" => "Home",
"blog" => "Blog",
"about" => "About me"
);
?>
And then:
<?php
$lang = array();
include ('translations/nav-translation/en.php');
include ('translations/nav-translation/lv.php');
?>
Seems a lot less complicated than any other suggestion.
To create a multilingual PHP site, I'd suggest using a function that checks the language the user has specified and then loading the text from a database or use JSON.
Using JSON
Create a file with a .txt extension, create your translations in JSON format and read it via PHP, to read the file in PHP use:
$json = json_decode(file_get_contents($file),TRUE);
You can then use the JSON data to set variables within PHP to display the correct language.
Using a database
Have your database setup like this:
---------------------------
Lang | Short | Text
---------------------------
In your database, set up as many languages as you want, have the lang column the two-letter abbreviation of the language name, the short should be the name of the text, so if it was the home page title, name the short home-title and then the text should be the text that you want to be displayed in your desired language.
Using a database will allow you to add/edit languages and translations via the database.
$path = 'translations/nav-translation';
$user_lang = 'nl'; // determine what the user actually wants
$fallback_lang = 'en';
if (file_exists("{$path}/{$user_lang}.php")) {
include ("{$path}/{$user_lang}.php");
} else {
include ("{$path}/{$fallback_lang}.php"); // nominate a default
}
In the language files (e.g. translations/nav-translation/en.php), offer a fully formed associative array:
$lang = [
"home" => "Home",
"blog" => "Blog",
"about" => "About me"
];
Then, back in your original file after the conditional include call, you can reference $lang['home'] or [cringe] use extract()* to generate variables like $home.
*note, I have never, ever used extract() in any of my projects, there are risks in using it -- I'm just saying you could.

Can we edit a mustache template in runtime?

Can I add new nodes to mustache template at run-time in PHP? Let's say below is a code where ProductDetails will contain few single products:
{{#ProductDetails}}
{{#SingleProduct}}
{{OldDetail}}
{{/SingleProduct}}
{{/ProductDetails}}
I want to add a new node like {{NewDetail}} just after {{OldDetail}} through some function in run-time(i.e just before I am compiling the template as these templates have been shipped to customers in such a way that only code to compile can be changed but not the template)? I don't want to do string manipulation(customers created few new templates with above parameters present at least but the spacing may change & few new entries can be added by them around nodes). Does mustache library provide any functions for that?
If I were you, I will try Lambdas.
Template.mustache will be like this:
{{#ProductDetails}}
{{#SingleProduct}}
{{OldDetail}}
{{/SingleProduct}}
{{/ProductDetails}}
And codes will be like:
$Mustache = new Mustache_Engine(['loader' => new Mustache_Loader_FilesystemLoader($YOUR_TEMPLATE_FOLDER),]);
$Template = $Mustache->loadTemplate('Template');
$OriginalOldDetail = '<h1>this is old detail</h1>';
echo $Template->Render([
'ProductDetails' => true,
'SingleProduct' => true,
'OldDetail' => function($text, Mustache_LambdaHelper $helper){
// Render your original view first.
$result = $helper->render($text);
// Now you got your oldDetail, let's make your new detail.
#do somthing and get $NewDetail;
$NewDetail = $YourStuff;
// If your NewDetail is some mustache format content and need to be render first.
$result .= $help->render($NewDetail);
// If is some content which not need to be render ? just apend on it.
$result .= $NewDetail;
return $result;
}
]);
Hope that will help.
(English is not my first language so hope you can understand what I'm talking about.)

Wordpress “PHP inside of PHP“ – Integrate qTranslate with Meta Box

For a Website (Wordpress) I want to display dates with the well-known plugin Meta Box and the Website should be provided in English as well as in German, with the plugin qTranslate.
German and English date formats are different: German: dd.mm.y (31.12.16), English: mm/dd/y (12/31/16). So to display the right format according to the language chosen by/for the visitor, the two plugins need to work together.
This is how I would display the date without any language option:
<?php echo rwmb_meta( 'exhibition_meta_beginning' ); ?>
This is how I would display translating text on the website outside of the post- and page-contents (like the site navigation):
<?php _e("[:en]Current[:de]Aktuell[:]"); ?>
My question now is, how I can join the two functions. If it helps, I would be fine with splitting the exhibition_meta_beginning in exhibition_meta_beginning_DE and exhibition_meta_beginning_EN, which would mean that I had to enter every date twice when creating a new instance/post, one in German and once in English format.
I haven't found anything useful yet – yes, there are mentions of that and there is some kind of way to use Custom Fields (which is the core basis of Meta Box) with qTranslate, but nothing seems to work and my knowledge in PHP is the bare minimum.
The input fields for the meta data being dates (and times) are defined in a separate PHP file like this (standard Meta Box procedure):
array(
'name' => 'Beginn der Ausstellung',
'id' => $prefix . 'beginn',
'type' => 'date',
'format' => 'dd.mm.y'
),
Neither did it work to implement the bilinguality into the format value right there (it thinks that it is a date's format not a language tag when [:en]... appears there), nor something like that in the part where the data is displayed (sorry for the amateurish attempt):
<?php __("[:en] echo rwmb_meta( 'exhibition_meta_beginn_EN' )[:de]echo rwmb_meta( 'exhibition_meta_beginn_DE' )[:]"); ?>
Thanks!
You can do it like this,
$en = rwmb_meta( 'exhibition_meta_beginn_EN' );
$de = rwmb_meta( 'exhibition_meta_beginn_DE' );
echo __('[:en]'.$en.'[:de]'.$de.'[:]');
or create a function that return the value based on language
function __show_based_on_lang($en, $de) {
return ( qtranxf_getLanguage() == 'en') ? $en : $de ;
}
then to use the function you can just have it like this,
echo __show_based_on_lang( rwmb_meta( 'exhibition_meta_beginn_EN' ), rwmb_meta( 'exhibition_meta_beginn_DE' ) );

MediaWiki: Show user name in skin

This should be fairly simple for anyone familiar with MediaWiki, but it's stumping me for me because being me.
I'm working on a skin, and I need to show the currently logged in user's name in a top bar - let's assume in plain text, for simplicity's sake, with changes via CSS.
Initially, I was planning on using the automatically generated one used in the personal tools bar, but since the generating line in the skin is
<?php $this->renderNavigation( 'PERSONAL' ); ?>
, it's inseparable from there. I looked in User.php and found its generation line:
public function getUserPage() {
return Title::makeTitle( NS_USER, $this->getName() );
}
So, I figure I might be able to use this function somehow, but I have very little knowledge of PHP, and am unsure how.
EDIT: It appears that this is used for the generation in the personal tools line itself, but again, I'm not sure how to adapt this.
$personal_urls['userpage'] = array(
'text' => $this->username,
'href' => &$this->userpageUrlDetails['href'],
'class' => $this->userpageUrlDetails['exists'] ? false : 'new',
'active' => ( $this->userpageUrlDetails['href'] == $pageurl )
);
Could I duplicate this into a separate function, and make something like the following?
<?php $this->renderNavigation( 'USERNAME' ); ?>
You can use this code:
<?php echo htmlspecialchars($this->getSkin()->getUser()->getName()); ?>
Or, as the User class has a __ToString() magic method:
<?php echo htmlspecialchars($this->getSkin()->getUser()); ?>
Sources :
The SkinTemplate class in MediaWiki code documentation
The User class in the same documentation
CurrentUsers
http://www.mediawiki.org/wiki/Extension:CurrentUsers
GetUserName
http://www.mediawiki.org/wiki/Extension:GetUserName
Modify these extension for your needs
If you indeed just want the username inserted somewhere into the skin HTML, this should do it:
<?php echo htmlspecialchars( $this->username ); ?>

Mustache php gettext()

I am experimenting with kostache, "mustache for kohana framework".
Is there any way I can use simple PHP functions in mustache template files.
I know logic and therefore methods are against logic-less design principle, but I'm talking about very simple functionality.
For example:
gettext('some text') or __('some text')
get the base url; in kohana -> Url::site('controller/action')
Bobthecow is working on an experimental feature that will allow you to call a function as a callback.
Check out the higher-order-sections branch of the repository and the ticket to go with it.
You could use "ICanHaz" http://icanhazjs.com/
and then you can declare your mustache templates as
<script id="welcome" type="text/html">
<p>Welcome, {{<?php echo __('some text') ?>}}! </p>
</script>
Well, you can do this now with Bobthecow's implementation of Mustache Engine. We need anonymous functions here, which are passed to the Template Object along with other data.
Have a look at the following example:
<?php
$mustache = new Mustache_Engine;
# setting data for our template
$template_data = [
'fullname' => 'HULK',
'bold_it' => function($text){
return "<b>{$text}</b>";
}
];
# preparing and outputting
echo $mustache->render("{{#bold_it}}{{fullname}}{{/bold_it}} !", $template_data);
In the above example, 'bold_it' points to our function which is pasalong withwith other data to our template. The value of 'fullname' is being passed as a parameter to this function.
Please note that passing parameters is not mandatory in Mustache. You can even call the php function wothout any parameters, as follows:
<?php
# setting data for our template
$template_data = [
'my_name' => function(){
return 'Joe';
}
];
# preparing and outputting
echo $mustache->render("{{my_name}} is a great guy!", $template_data); # outputs: Joe is a great guy!
Credits: http://dwellupper.io/post/24/calling-php-functions-for-data-in-mustache-php

Categories