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.
Related
i'm working on my own way of handling a bilingual site. my method should allow proper search engine indexing and will keep everything on one page without external files.
one function would handle which content to display:
<?
function l($en, $fr){
echo ($_GET['lang'] === 'fr') ? $fr : $en ;
}
?>
then the appropriate text will display according to language in URL (/?lang=en)
<h1><? l('welcome!', 'bienvenue!') ?></h1>
for an image this is my solution:
<img src="<? l('hi-en.png', 'hi-fr.png')?>" width="100" height="20">
can anyone name drawbacks to this method if used? is it unusual to have a single function handle language for pages which would include all language content?
The general idea of using a singleton or global function like your l function is very common. You're definitely on the right track!
Your method does have some drawbacks, though:
If you have the same text or image that appears in numerous places in the code, you need to maintain the translation in every place.
Updating or correcting a translation requires wading through code, which is very difficult for inexperienced coders or non-coders (say, if you have a translator helping you).
If you were ever to add a new language, you would have to modify every source file, which would be excruciating. This may be unlikely, but if it ever happened, you'd be rather cross with yourself.
A more typical solution is to have the translations located in a separate file, either as a simple hash or as a structured data format like XML, and then your l function would just look like l('welcome'); the parameter is a key, and l will look up the correct translation in the given language from the separate file.
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/)
I am just wondering if its normal to embed PHP in the HTML, or is it considered dirty/unprofessional. For example consider following lines:
<? if($photo == 0) { ?>
<div class ="reminder">Hey <?=$name;?>, You don't have any photo. </div>
<? } else { ?>
<div class ="ok">Do you want to change your photo? </div>
<? } ?>
Is this kind of code ok? How the similar work can be done in a clean/professional way (without PHP frameworks? )
Thanks.
As long as you keep the logic of your program outside the html, it is ok. You need to mix it in your templates, for example. Template-engines like smarty replace the {$myVar} with < ? php echo $myVar; ? > (simply spoken), so it is not possible to avoid it completely. But things like
<?php
include "db.php";
connect_db();
// check login
echo "< html >< head><body>...";
?>
is NOT good practice, because you mix everything together: program logic (login-check, db-stuff) and output (echo html). Just have a look at the MVC and keep the "separation of concerns" in mind.
Your example looks ok because you have only that logic in your html which is needed to control the output directly. But calculating the value of $photo, depending on a db entry for example, would NOT be good in your html, because this is program logic. Output (HTML) and logic should be devided all the time.
It's very normal, whether it's good or not is a completely separate topic. It's really all about the size of your project and your requirements for maintainability/flexibility.
If it's a small project, just do what you have to in order to get it done. However a point exists at which it becomes unwieldy to develop without a framework. This is all very subjective and varies from project to project, but this is the general principle.
It's OK to use PHP in templates but many people prefer to work with a templating language because it forces separation and ensures you don't litter your templatse with loads of PHP. If you do go down the template route Twig and Smarty are quite good since they compile the template into PHP which speeds things up.
If you're writing PHP in your templates try to follow some best practise coding standards to keep things neat. For example:
Use full <?php tags for compatibility.
When writing any loops instead of curly braces use colons. To end the statement you need to explicitly write it as endforeach/endif/endwhile/etc. This makes PHP templates more readable.
If you have a lot of logic move this into an external PHP file to keep the PHP in your template short and readable
If there is only one PHP statement in your PHP tag you don't need to end it with a semi-colon. Again, helps readability
An example:
<?php if ($photo == 0): ?>
<div class ="reminder">Hey <?php echo $name ?>, You don't have any photo.</div>
<?php else: ?>
<div class ="ok">Do you want to change your photo?</div>
<?php endif ?>
See more at:
http://www.php.net/manual/en/control-structures.alternative-syntax.php
http://framework.zend.com/manual/en/coding-standard.overview.html
for that you can use smarty templete .... it improves your coding style and works fast ... visit smarty and try it, it's really awesome
From what I have read either will work, but most people just use the echo statements for small, conditional html.
I try to keep this at a minimum, because i find it harder to debug it with all the
< ? } ?>
flowing around in the code (wordpress theme gurus does this alot)
There will be many opinions about this. Mixing HTML and PHP can become very messy, but this looks fine. Many professionals work just this way. If it works for you, it's good.
To make it more readable, I tend to keep the brackets on separate lines, just so you can be sure to be able to find them all easily, but thats just me.
there was an answer from guy named alexn
Dunno why did he delete it, it's looks best answer to me, so, I am only reproducing it:
I would say that's the way to go. You
have a nice, clean separation of PHP
and HTML.
Here's another option:
<? if($photo == 0): ?>
<div class ="reminder">Hey <?=$name?>, You don't have any photo. </div>
<? else: ?>
<div class ="ok">Do you want to change your photo? </div>
<? endif ?>
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(); ?>