I would like to add translation to my site to all sorts of languages.
I thought of defining chunks of code in different language files,
Is that possible to create seperate files for translation in something like this manner ? :
the generic file:
// index.php
// say $_SESSION['lang'] = rtlLANG;
<?php include($_SESSION['lang'].".php");?>
<html>
<body>
<?php MAIN_WELCOME_MESSAGE; ?>
</body>
</html>
// some rtlLANG.php
define("MAIN_WELCOME_MESSAGE","
echo '<table style="direction:ltr;">';
echo 'welcome rtl language readers';
");
// some ltrLANG.php
define("MAIN_WELCOME_MESSAGE","
echo '<table style="direction:rtl;">';
echo 'welcome rtl language readers';
");
is it possible to somehow define these chunks of code ? (I know that not as it is at least)
How can I implement different ways to layout my content for each language otherwise ?
Use the standard (cross language, too) library gettext. http://php.net/gettext
there are many ways for implementing multilang support. here's my suggestion:
from my experience with html/css it's best to create 2 versions of the design - rtl and ltr. if you use MVC you could set a dir for the views (or templates).
you should have a list of languages, and for each you need to say whether it's ltr or rtl.
now for the actual translation: in your views/templates or html code/error and notice messages you can load the actual text. you can either write your own code, or (i'd recommend) use gettext (http://www.gnu.org/s/gettext/)
Related
I am asking this purely for educational purposes, while browsing for some reference information for HTML5, I came across the lang attribute, while I understand its a way of defining a language, if I were to say make a multi language site, rather than make every page again I would have assumed it would be a way to hide various divs based on the language of the browser i.e.
<div lang='en'>Hello</div>
<div lang='ja'>こんいちは</div>
So my first thought was if my browser was set to english it should show only the english tag, however upon further reading it seems that the lang tag only seems to tell the browser what language it is and added support for TTS, Braile, and other things.
Is this correct, or am I just being oblivious to some other underlying use of it?
If it is just a reader or something similar, would the best way of swapping languages on a single html/php site be:
<?php if ($_GET['lang'] == "en") { ?>
<div>Hello</div>
<?php } else if ($_GET['lang'] == "ja") { ?>
<div>こんいちは</div>
<?php } else { ?>
<div>Language not supported</div>
<?php } ?>
While I have been a programmer for many years, there are many small things like this that I have simply not come across before.
Regards
You could use CSS to show or hide elements depending on their lang attribute. You would just waste a lot of bandwidth.
Language Tag
The purpose of the language tag is to enable you to mark links, quotes or the like, so you can style them, e.g., add a british flag to a link that points to an English article from your Japanese blog post, and to enable screen readers to provide the correct pronounciation.
Translations
If you want to provide translated text depending on a parameter, you should do the translation outside of your HTML code (just like any other processing). The mix just makes code illegible and a maintenance nightmare.
A common solution is to provide translation data in separate language files, mostly .ini files. In your case, they could look like:
languages/ja.ini:
LANG="ja"
HELLO="こんいちは"
languages/en.ini:
LANG="en"
HELLO="Hello"
Now, you can use those in your HTML files.
index.php:
<?php
$language = $_GET['lang'] ?: 'en';
$translation = "languages/{$language}.ini";
if (!is_readable($translation)) {
throw new \RuntimeException("Language file {$translation} not found");
}
$_ = parse_ini_file($translation);
?>
<div lang="<?= $_['LANG']; ?>"><?= $_['HELLO']; ?></div>
Both your PHP and HTML code are easier to understand, and the language files are easy to maintain.
I have been designing websites for a while now, but there is one thing that I have never been quite sure of when using PHP and HTML. Is it better to have the whole document in PHP and echo HTML like so:
<?php
doSomething();
echo "<div id=\"some_div\">Content</div>";
?>
Or have a HTML file like so and just add in the PHP:
<html>
<body>
<?php doSomething(); ?>
<div id="some_div">Content</div>
</body>
</html>
It seems tidier to echo HTML, especially if lots of PHP gets used throughout the page, but doing so loses all formatting of the HTML i.e. colors in the IDE etc.
There are varying opinions on this. I think there are two good ways:
Use a templating engine like Smarty that completely separates code and presentation.
Use your second example, but when mixing PHP into HTML, only output variables. Do all the code logic in one block before outputting anything, or a separate file. Like so:
<?php $content = doSomething();
// complex calculations
?>
<html>
<body>
<?php echo $content; ?>
<div id="some_div">Content</div>
</body>
</html>
Most full-fledged application frameworks bring their own styles of doing this; in that case, it's usually best to follow the style provided.
I think this would depend on your group's or your own decided convention. And it can and should vary depending on what type of file you're working in. If you follow the MVC pattern then your views should be the latter. If you're writing a class or some non-output script/code then you should use the former.
Try to keep a separation of display or formatting of output and the logic that provides the data. For instance let's say you need to make a quick page that runs a simple query and outputs some data. In this case (where there is no other existing infrastructure or framework) you could place the logic in an include or in the top or the bottom of the file. Example:
<?php
# define some functions here that provide data in a raw format
?>
<html>
<body>
<?php foreach($foo = data_function($some_parameter) as $key => $value): ?>
<p>
<?=$value;?>
</p>
<?php endforeach; ?>
</body>
</html>
Or you could place the logic and function definitions in an include file or at the bottom of the file.
Now if you're producing some sort of class that has output (it really shouldn't) then you would echo the HTML or return it from the method being called. Preferably return it so that it can be output whenever and however the implementer would like.
The syntax highlighting is an important benefit of the second method, as you said. But also, if you're following good practices where logic and presentation are separated, you will naturally find that your files that contain HTML are almost entirely HTML, which then, naturally, leads to your second method again. This is the standard for MVC frameworks and the like. You'll have a bunch of files that are all PHP, doing logic, and then when that's done they'll include a presentation file which is mostly HTML with a sprinkling of PHP.
Simple:
More PHP - close HTML in PHP. When you generate HTML code in PHP, when you are doing something like a class, so it is better to make it in echo.
Less PHP - close PHP in HTML. This is stuff like just putting vars into fields of HTML stuff, like forms... And such.
The best approach is to separate the HTML from the PHP using template system or at least some kind of HTML skeleton like:
<main>
<header/>
<top-nav/>
<left-col>
<body />
</left-col>
<right-col />
<footer/>
</main>
Each node represents a template file e.g. main.php, hrader.php and so on. Than you have to separate the PHP code from the templates as something like functions.php and fineally use your second approach for template files and keeping functions clean of "echos" and HTML.
If you can, use a template engine instead.
Although it is slightly easier at first to mix your HTML and PHP, separating them makes things much easier to maintain later on.
I would recommend checking out TemplateLite which is based on Smarty but is a little more light weight.
I've reached a conclusion that using views in MVC framework e.g. Laravel, Yii, CodeIgniter is the best approach even if you are not displaying the html straight away.
Inside the view do all the echoing and looping of prepared variables, don't create or call functions there, unless formatting existing data e.g. date to specific format date('Y-m-d', strtodate(123456789)). It should be used only for creating HTML, not processing it. That's what frameworks have controllers for.
If using plain PHP, create you own view function to pass 3 variables to - html file, array of variables, and if you want to get output as string or print it straight away for the browser. I don't find a need for it as using frameworks is pretty much a standard. (I might improve the answer in the future by creating the function to get view generated HTML) Please see added edit below as a sample.
Frameworks allow you to get the HTML of the view instead of displaying it. So if you need to generate separate tables or other elements, pass the variables to a view, and return HTML.
Different fremeworks may use various type of templating languages e.g. blade. They help formatting the data, and essentially make templates easier to work with. It's also not necessary to use them for displaying data, or if forced to use it by the framework, just do required processing before posting the variables, and just "print" it using something like {{ yourVariable }} or {{ yourVariable.someProperty }}
Edit: here's a plain PHP (not framework PHP) - simple-php-view repository as a sample view library that allows to generate HTML using variables. Could be suitable for school/university projects or such where frameworks may not be allowed.
The repository allows to generate HTML at any time by calling a function and passing required variables to it, similar to frameworks. Separately generated HTML can then be combined by another view.
It depends on the context. If you are outputting a lot of HTML with attributes, you're going to get sick of escaping the quotation marks in PHP strings. However, there is no need to use ?><p><? instead of echo "<p>"; either. It's really just a matter of personal taste.
The second method is what I usually use. And it was the default method for me too. It is just to handy to get php to work inside html rather than echo out the html code. But I had to modify the httpd.conf file as my server just commented out the php code.
I have been designing websites for a while now, but there is one thing that I have never been quite sure of when using PHP and HTML. Is it better to have the whole document in PHP and echo HTML like so:
<?php
doSomething();
echo "<div id=\"some_div\">Content</div>";
?>
Or have a HTML file like so and just add in the PHP:
<html>
<body>
<?php doSomething(); ?>
<div id="some_div">Content</div>
</body>
</html>
It seems tidier to echo HTML, especially if lots of PHP gets used throughout the page, but doing so loses all formatting of the HTML i.e. colors in the IDE etc.
There are varying opinions on this. I think there are two good ways:
Use a templating engine like Smarty that completely separates code and presentation.
Use your second example, but when mixing PHP into HTML, only output variables. Do all the code logic in one block before outputting anything, or a separate file. Like so:
<?php $content = doSomething();
// complex calculations
?>
<html>
<body>
<?php echo $content; ?>
<div id="some_div">Content</div>
</body>
</html>
Most full-fledged application frameworks bring their own styles of doing this; in that case, it's usually best to follow the style provided.
I think this would depend on your group's or your own decided convention. And it can and should vary depending on what type of file you're working in. If you follow the MVC pattern then your views should be the latter. If you're writing a class or some non-output script/code then you should use the former.
Try to keep a separation of display or formatting of output and the logic that provides the data. For instance let's say you need to make a quick page that runs a simple query and outputs some data. In this case (where there is no other existing infrastructure or framework) you could place the logic in an include or in the top or the bottom of the file. Example:
<?php
# define some functions here that provide data in a raw format
?>
<html>
<body>
<?php foreach($foo = data_function($some_parameter) as $key => $value): ?>
<p>
<?=$value;?>
</p>
<?php endforeach; ?>
</body>
</html>
Or you could place the logic and function definitions in an include file or at the bottom of the file.
Now if you're producing some sort of class that has output (it really shouldn't) then you would echo the HTML or return it from the method being called. Preferably return it so that it can be output whenever and however the implementer would like.
The syntax highlighting is an important benefit of the second method, as you said. But also, if you're following good practices where logic and presentation are separated, you will naturally find that your files that contain HTML are almost entirely HTML, which then, naturally, leads to your second method again. This is the standard for MVC frameworks and the like. You'll have a bunch of files that are all PHP, doing logic, and then when that's done they'll include a presentation file which is mostly HTML with a sprinkling of PHP.
Simple:
More PHP - close HTML in PHP. When you generate HTML code in PHP, when you are doing something like a class, so it is better to make it in echo.
Less PHP - close PHP in HTML. This is stuff like just putting vars into fields of HTML stuff, like forms... And such.
The best approach is to separate the HTML from the PHP using template system or at least some kind of HTML skeleton like:
<main>
<header/>
<top-nav/>
<left-col>
<body />
</left-col>
<right-col />
<footer/>
</main>
Each node represents a template file e.g. main.php, hrader.php and so on. Than you have to separate the PHP code from the templates as something like functions.php and fineally use your second approach for template files and keeping functions clean of "echos" and HTML.
If you can, use a template engine instead.
Although it is slightly easier at first to mix your HTML and PHP, separating them makes things much easier to maintain later on.
I would recommend checking out TemplateLite which is based on Smarty but is a little more light weight.
I've reached a conclusion that using views in MVC framework e.g. Laravel, Yii, CodeIgniter is the best approach even if you are not displaying the html straight away.
Inside the view do all the echoing and looping of prepared variables, don't create or call functions there, unless formatting existing data e.g. date to specific format date('Y-m-d', strtodate(123456789)). It should be used only for creating HTML, not processing it. That's what frameworks have controllers for.
If using plain PHP, create you own view function to pass 3 variables to - html file, array of variables, and if you want to get output as string or print it straight away for the browser. I don't find a need for it as using frameworks is pretty much a standard. (I might improve the answer in the future by creating the function to get view generated HTML) Please see added edit below as a sample.
Frameworks allow you to get the HTML of the view instead of displaying it. So if you need to generate separate tables or other elements, pass the variables to a view, and return HTML.
Different fremeworks may use various type of templating languages e.g. blade. They help formatting the data, and essentially make templates easier to work with. It's also not necessary to use them for displaying data, or if forced to use it by the framework, just do required processing before posting the variables, and just "print" it using something like {{ yourVariable }} or {{ yourVariable.someProperty }}
Edit: here's a plain PHP (not framework PHP) - simple-php-view repository as a sample view library that allows to generate HTML using variables. Could be suitable for school/university projects or such where frameworks may not be allowed.
The repository allows to generate HTML at any time by calling a function and passing required variables to it, similar to frameworks. Separately generated HTML can then be combined by another view.
It depends on the context. If you are outputting a lot of HTML with attributes, you're going to get sick of escaping the quotation marks in PHP strings. However, there is no need to use ?><p><? instead of echo "<p>"; either. It's really just a matter of personal taste.
The second method is what I usually use. And it was the default method for me too. It is just to handy to get php to work inside html rather than echo out the html code. But I had to modify the httpd.conf file as my server just commented out the php code.
What's the best way (to avoid modifying repeated code) to building multilingual web pages?
I know how to build a multilingual web page without having to modify CSS and Javascript files.
But I can't think of a neat solution for HTML and Php files. Because if I have HTML or Php files for each language, I would have to modify each one if, for instance, I add an extra div or other element.
I was thinking to have something like this:
<div id="multilingual div">
<p><?php echo($multilingual-paragraph); ?></p>
</div>
(So, even if I modify these elements, I will just do it once, because the text that is in other language will show up from the variable).
I don't know Php, so I don't know how to tell Php to display a different variable according to the language (I think it has something to do with IF conditions)
Is this a good way of creating multilingual web pages or there are other methods?
(So with this
Check out the gettext() function. You don't really need to build different files for different languages. Altough, you'll have to struggle with the translation files.
You can implement a constants-solution for output messages. Using APC's cache functions, you can store multiple messages inside the cache and load them according to the pages you're viewing (this might not be an easy solution though, you need to know php for this).
This would allow you to maintain an array with values for each language in the cache. For example:
apc_constants_define('en',array('welcomeMessage'=>'Welcome!'));
apc_constants_define('es',array('welcomeMessage'=>'Bienvenidos!'));
apc_constants_define('de',array('welcomeMessage'=>'Willkommen!'));
through AJAX/select form, you can allow the user to choose the language they want to view your pages.
This language would be stored inside a session:
$_SESSION['language'] = 'en';
Next, on every page's top, you should check the session (simple switch statment) and load the constants from the cache accordingly.
apc_load_constants($_SESSION['language']);
then your html page would look like this:
<h1><?php echo welcomeMessage; ?></h1>
This is, as I see it, the most efficient way of internationalizing your website, and with an easily maintainable system, that doesn't require you to delve into the code when you want to translate your page to Romanian.
As you said, you have php and html language files, one way is to go like this:
$lang = '';
switch ($lang_file)
{
case 'en.php': $lang = 'whatever'; break;
case 'fr.php': $lang = 'whatever'; break;
// etc
}
<div id="multilingual div">
<p><?php echo $lang; ?></p>
// or you may include files
<p><?php include_once ($lang); ?></p>
</div>
Most HTML in a large website is duplicated across pages (the header, footer, navigation menus, etc.). How do you design your code so that all this duplicate HTML is not actually duplicated in your code? For example, if I want to change my navigation links from a <ul> to a <ol>, I'd like to make that change in just one file.
Here's how I've seen one particular codebase handle this problem. The code for every page looks like this:
print_top_html();
/* all the code/HTML for this particular page */
print_bottom_html();
But I feel uncomfortable with this approach (partially because opening tags aren't in the same file as their closing tags).
Is there a better way?
I mostly work with PHP sites, but I'd be interested in hearing solutions for other languages (I'm not sure if this question is language-agnostic).
I'm not a php programmer, but I know we can use a templating system called Smarty that it works with templates(views), something like asp.net mvc does with Razor.
look here http://www.smarty.net/
One solution at least in the case of PHP (and other programming languages) is templates. Instead of having two functions like you have above it would instead be a mix of HTML and PHP like this.
<html>
<head>
<title><?php print $page_title ?></title>
<?php print $styles ?>
<?php print $scripts ?>
</head>
<body>
<div id="nav">
<?php print $nav ?>
</div>
<div id="content">
<?php print $content ?>
</div>
</body>
</html>
Each variable within this template would contain HTML that was produced by another template, HTML produced by a function, or also content from a database. There are a number of PHP template engines which operate in more or less this manner.
You create a template for HTML that you would generally use over and over again. Then to use it would be something like this.
<?php
$vars['nav'] = _generate_nav();
$vars['content'] = "This is the page content."
extract($vars); // Extracts variables from an array, see php.net docs
include 'page_template.php'; // Or whatever you want to name your template
It's a pretty flexible way of doing things and one which a lot of frameworks and content management systems use.
Here's a really, really simplified version of a common method.
layout.php
<html>
<body>
<?php echo $content; ?>
</body>
</html>
Then
whatever_page.php
<?php
$content = "Hello World";
include( 'layout.php' );
Sounds like you need to use include() or require()
<?php
include("header.inc.php");
output html code for page
include("footer.inc.php");
?>
The header and footer files can hold all the common HTML for the site.
You asked for how other languages handle this, and I didn't see anything other than PHP, so I encourage you to check out Rails. Rails convention is elegant, and reflects #codeincarnate 's version in PHP.
In the MVC framework, the current view is rendered inside of a controller-specific layout file that encapsulates the current method's corresponding view. It uses a "yield" method to identify a section where view content should be inserted. A common layout file looks like this:
<html>
<head>
<% #stylesheet and js includes %>
<body>
<div id="header">Header content, menus, etc…</div>
<%= yield %>
<div id="footer">Footer content</div>
</body>
</html>
This enables the application to have a different look and feel or different navigation based on the controller. In practice, I haven't used different layout files for each controller, but instead rely on the default layout, which is named "application".
However, let's say you had a company website, with separate controllers for "information", "blog", and "admin". You could then change the navigation for each in a clean and unobtrusive manner by handling the different layout views in their respective layout files that correspond to their controllers.
You can always set a custom layout in the controller method by stating:
render :layout => 'custom_layout'
There are also great helper methods built into Rails so you don't have to rely on $global variables in PHP to ensure your CSS and Javascript paths are correct depending on your development environment (dev, staging, prod…). The most common are:
#looks in public/stylesheets and assumes it's a css file
stylesheet_link_tag "filename_without_extension"
#looks in public/javascripts and assumes it's a js file
javascript_include_tag "jquery"
Of course, each of these sections could be expounded upon in much greater detail and this is just brushing the surface. Check out the following for more detail:
http://guides.rubyonrails.org/layouts_and_rendering.html
What you suggested works OK. As long as print_top_html and print_bottom_html stay in sync (and you can use automated tests to check this), then you never need to worry about them again, leaving you to focus on the real content of the site -- the stuff in the middle.
Alternatively, you can combine print_top_html and print_bottom_html into a single call, and send it HTML code (or a callback) to place in the middle.
I use the partials system of Zend_View (very similar to Rails). A partial is essentially a small HTML template that has its own variable scope. It can be called from inside views like:
<?php echo $this->partial('my_partial.phtml', array( 'var1' => $myvar ));
The variables that get passed into the construct get bound to local variables inside the partial itself. Very handy for re-use.
You can also render a partial from inside normal code, if you're writing a helper object where you have more complex logic than you'd normally feel comfortable putting in a view.
public function helperFunction()
{
// complex logic here
$html = $this->getView()->partial('my_partial.phtml', array('var1' => $myvar ));
return $html;
}
Then in your view
<?php echo $this->myHelper()->helperFunction(); ?>