Change text depending on language - php

I'm using Wordpress with a language switcher to switch between various languages. Within the templates I'm using this piece of code to switch hard coded text.
<?php if(ICL_LANGUAGE_CODE == 'en') { ?>
This is english
<?php } else { ?>
This is another language
<?php } ?>
I have a sidebar but it's created via various widgets so I can't put the same fix in place.
Using jquery, how can I target all the text within a specific div and replace it with something else?
If I put that jquery within the code above then that should work shouldn't it?

jQuery/JS is Client, PHP is server, so that being said, there is one chance to inject PHP into JavaScript, and that is at the run-time of the page. You can probably do something like:
$(document).ready(function() {
var language = '<?php echo ICL_LANGUAGE_CODE?>';
if (language == "EN") {
$("#IDOFDIV").html("NEW HTML HERE");
}
});

Related

HTML lang Tag display language

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.

Conditional php include in wp using media queries and javascript

I may be going about this all wrong, but here goes.... Im trying to use JavaScript in a WP theme file to do conditional PHP includes based on CSS media queries and pseudo-elements.
In the CSS I use a media query to check for mobile devices in portrait mode, add a hidden :after element to the body under this query with content="mobile_portrait" attribute.
I then wanted to go on the homepage template and use JavaScript like this:
var size = window.getComputedStyle(document.body,':after').getPropertyValue('content');
if (size == 'mobile_portrait') {
<?php
add_action( 'genesis_after_header', 'do_this' );
function do_this() {
require(CHILD_DIR.'/do_this.php');
}
?>
}
else {
<?php
add_action( 'genesis_after_header', 'do_the_other' );
function do_the_other() {
require(CHILD_DIR.'/do_the_other.php');
}
?>
}
It seems like WP is skipping the JavaScript and parsing the PHP because if I take out the else it just loads do_this.php whether the Java check returns true or false, if I leave the else in, it breaks the site :(
Ideas about what im doing wrong? or a better way to load PHP files based on media queries?
Thanks in advance
PHP and Javascript cannot be used interchangeably like you are trying to do.
PHP is the renderer, it is building the output (building the Javascript)
The PHP will be run, regardless of where they are put inside a Javascript conditional like you have, as the Javascript conditionals have no bearing on them being executed.
==
Now to add a solution:
Maybe use the javascript like you have setup simply redirect to the phpfile you want to run for a given view:
var size = window.getComputedStyle(document.body,':after').getPropertyValue('content');
if (size == 'mobile_portrait') {
window.location = '<?= CHILD_DIR.'/do_this.php'; ?>';
}
else {
window.location = '<?= CHILD_DIR.'/do_the_other.php'; ?>';
}
So have different pages that do the necessary includes based on the media query

Is using PHP if/else within JS bad practice?

I'm building a custom template for WordPress and in a couple places I've used PHP if else statements like the following example within the JS in the footer. It works fine but I'm wondering if this is considered "bad practice" and if so what is a better way to handle it?
<script type="text/javascript">
var $submenu = $('.submenu');
// SUBMENU animation
<?php if ( in_category('Collection') == false ) { ?> // if not a Collection subpage
$('.menu li a').each(function() {
if ( $(this).text() == 'Collection' ) { // If is Collection link show submenu on hover
$(this).mouseenter(function() {
$submenu.slideDown();
});
} else { // else close submenu on hover over other menu links
$(this).mouseenter(function() {
$submenu.slideUp();
});
}
});
$('.nav').mouseleave(function() { // close submenu
$submenu.slideUp();
});
<?php } else { ?> // If a Collection subpage always show subnav
$submenu.show();
<?php } ?>
</script>
Whilst there isn't anything really wrong with mixing PHP and JavaScript, I personally find it quite awkward to read and modify, plus it makes moving that code around tricky. For example if you decided to export that JavaScript to an external file, which has numerous benefits:
<script src="myjs.js.php"></script>
This becomes clunky if your JavaScript needs to know certain values in order to calculate in_category('Collection') as you have to start using GET parameters (unless you are depending on session variables, which can get quite compex and unpredictable, especially through asset requests):
<script src="myjs.js.php?random_vars_required=123"></script>
Another point to be wary of is when having a JavaScript file that changes it's content depending on server-side logic, you have to be careful with what the browser is caching (to avoid these type of problems, it basically means you have to change the request URL for each possible outcome of the js file). i.e.
<script src="myjs.js.php?collection=true"></script>
<script src="myjs.js.php?collection=false"></script>
Another downside is by mixing PHP with JS you are likely to end up duplicating the PHP code in numerous places which goes against the DRY principal. This is why the suggested "export data to a javascript variable" is a much nicer idea. However it's best to avoid variables in the global js namespace if possible. Avoiding the global namespace can prove tricky though if you need to share the logic across multiple JavaScript files and don't wish to export your variables at the top of every file.
another possibility
If the logic you are testing is purely boolean in nature, and it also centres around page classification (or sub-region classification), the following is quite a nice way to handle what you are trying to achieve. It's nice mainly because it keeps your PHP and HTML together, and your JS separate.
The following should be placed in whatever template you use to generate your outer HTML:
<?php
$classes = array();
if ( in_category('Collection') ) {
$classes[] = 'collection';
}
$classes = implode(' ', $classes);
?>
<!--
obviously you'd render the rest of the html markup
I've removed it for simplicity
//-->
<body class="<?php echo $classes; ?>"></body>
Then in your JavaScript / jQuery:
if ( $('body.collection').length ) {
/// if collection sub page
}
else {
/// else do otherwise
}
If you'd rather not add a class to your body element, you could always define your boolean check based on something that already exists on one version of the page and not on the other. Although personally I like to keep things clean and only resort to those kind of checks when I know the HTML markup is not going to change much in the future.
Nearly all browsers that the greater world should be worrying about today support multiple classes on elements. So this means even if you have multiple things you wish to check for, as long as it makes sense, you can place these classes on your html or body tag and use jQuery's Sizzle implementation to find them for you.
Building javascript server-side is probably something we've all done, despite the main arguments for not doing so - namely that the js can't be (easily) validated (with eg. jsLint), and can't (easily) be put into a .js file - there's no point allowing the browser to cache just one of two or more possible versions of the script.
You could consider trading off server-side branching for client-side branching, which arguably makes the code more readable but, more importantly, is an intermediate step to my final suggestion (bear with me) :
var $submenu = $('.submenu');
// SUBMENU animation
var isCollection = <?php echo in_category('Collection') ? 'false' : 'true' ?>;
if ( !isCollection ) { // if not a Collection subpage
$('.menu li a').each(function() {
if ( $(this).text() == 'Collection' ) { // If is Collection link show submenu on hover
$(this).mouseenter(function() {
$submenu.slideDown();
});
} else { // else close submenu on hover over other menu links
$(this).mouseenter(function() {
$submenu.slideUp();
});
}
});
$('.nav').mouseleave(function() { // close submenu
$submenu.slideUp();
});
} else { // If a Collection subpage always show subnav
$submenu.show();
}
However, if the boolean isCollection could be determined by another means (eg. by enquiring some aspect of the DOM such as a data-xxx attribute), then you're cooking with gas. Only one version of the js script would be necessary; it could be easily validated with jsLint; and could be moved into a .js file if desired.
Of course you need to set the data-xxx attribute (or whatever) elsewhere in the server-side code (complete with an explanatory comment), which is a possible downside, but maybe not a big one.
Maybe not all js would be amenable to this approach but I think the example in the question would be.
To my mind, this is a viable way ahead on this occasion.
At least its not a sign of great code. There are alternatives:
Generate a JSON object and parse it in JavaScript
Dynamic inclusion of JS files
Just set conditions:
if(<?= (int)$mybool ?>) {
doSomething();
}

php excluding piece of html code?

I have a custom CMS here entitled phpVMS, and I want to exclude a piece of code, a banner for a single page. phpVMS is steered using templates, for instance, the main template that codes the general layout for all pages is entitled layout.tpl. So, like I said, this displays whatever is in the template, on all of the pages. I have however created a special control panel, and therefore require to exclude the banner, because it slightly destroys the theme of it. Is there any PHP code that excludes a piece of code on a single site? I need to remove a single div...
<div id="slideshow"></div>
...on a single page.
Basically, I could create a new template but this is a very long winded and unefficient way within this CMS, and the final result isn't that great - because I can't reinclude the mainbox div which is the box defining the content on the centre white bit of the theme - it's already in the layout.tpl.
I hope you can somehow help me, hope I've included enough information there.
Thanks.
I don't think you can do what you're asking in PHP, but you might be able to do this on the client-side, by either hiding the div (CSS display:none) or by removing it with JavaScript. You might be able to do something like:
<?php
include("layout.tpi");
if (condition)
{
// Javascript:
echo "<script>document.getElementById('slideshow').style.display = 'none';</script>";
// OR jQuery:
echo "<script>$('#slideshow').hide();</script>";
}
?>
If you use a variable to determine you don't want to include the div, you could do this:
<?php if ($include) { ?>
<div id="slideshow"></div>
<?php } ?>
OR
<?php
if (!$include)
echo "<!--";
?>
<div id="slideshow"></div>
<?php
if (!$include)
echo "-->";
?>
EDIT: Obviously, there is no good reason to use the second method. The second method will only comment out the HTML so it will still show up in the source.
I'm not sure if this is what you are looking for, but seems simple
<?
$template = true;
if($template) {
?>
<div id="slideshow"></div>
<?
}
?>
On the template, you could have some code that reads:
if($_SERVER['PHP_SELF'] == /*control panel file*/) {
//exclude
}else{
//include
}

Correct way of outputting a large block of HTML in PHP

I am learning PHP (no programming experience) from a book. The examples in the book use a strange way of outputting a large block of HTML conditionally. It closes the PHP tag inside the conditional, and reopens it after outputting the HTML. I understand (after some head scratching) how it works, but it seems like a dodgy, not-intended-to-be-used-like-this, workaround.
<?php
if(something == somethingelse) {
echo "some message";
}
else {
?>
<big-block-of-html>
</big-block-of-html>
<?php }
?>
The book did introduce the heredoc syntax, but never used it. Is there a right way of doing this? It would seem more intuitive to output the HTML from within PHP.
That's exactly how PHP is supposed to be used and is much more readable, elegant and robust than all alternatives*. I'd just go for a better indented style:
<?php
// normal
// code
// here
?>
<?php if ($foo) : ?>
<div>
<!-- more HTML -->
</div>
<?php endif; ?>
* Unless you go for completely code-free templates like Smarty of course...
Think about hide this block in other file.
Then you can create some function like this:
function get_some_big_block_content()
{
return get_file_contents('./your_big_block.html');
}
Then you can:
<?php
if(something == somethingelse) {
echo "some message";
}
else {
echo get_some_big_block_content();
}
?>
PHP allows multiple ways of doing this; picking one is mostly a matter of preference - for some, this is the most readable option, for some it's a horrible hack.
In all, inline HTML is hard to maintain in any form - if you're putting any serious effort into your website, consider some sort of templating system (e.g. Smarty) and/or framework (e.g. Symfony), otherwise you'll go mad from trying to maintain the PHP+HTML soup.
Use
<?php
if (something == somethingelse) {
echo "some message";
}
else {
echo "<big-block-of-html>
</big-block-of-html>";
}
?>

Categories