I want to use the laravel language data at the frontend part in the browser.
So I can use sprintf in js to show the same translation in frontend part.
I wish it could be an big javascript object. It would be very easy and nice to use.
Thanks in advance.
This is a situation I've dealt with myself and the answer is a bit awkward.
You can use Lang::get('file') to output the entire file as an array, which you can use with json_encode to do exactly what you want. But, as far as I know, you cannot get all language files. This probably has to do with the fact that Laravel cannot scan the directory for all file names without consuming a lot of disk resources, and does not do so normally. Language is handled with lazy loading in all applicable cases.
But! What you can do, is put all your JavaScript-related language in one file. I called mine widgets.php, and then do json_encode( Lang::get('widget') ) to get your JavaScript relevant language in one object.
Or, if you really do need all of it, you can build it manually.
$lang = ['auth', 'validation', 'etc'];
for ($files as $file)
{
$lang[$file] = Lang::get($file);
}
return json_encode($lang);
I guess easiest way to do that is to use cookies. Set coockie with Laravel:
$cookie = Cookie::make($name, $value);
Then read and parse it with JS:
var x = document.cookie;
Related
First, I know that JSON doesn't support comments. I'm using them anyway because I need to write little notes to make it easy for people who aren't tech-savvy to edit this file.
I'm using double-slash comments, but I can switch to slash-star if needed.
"campaignID": "230109-stock-shop", // this is the method I want
I know the technique of creating extra comment fields like this, but it doesn't fit my needs.
"__comment": "this ISN'T the method I want"
I'm working entirely in client-side Javascript/jQuery. When I import a file with comments, it - of course - doesn't work.
$.getJSON('file.json', function (json) {//do things})
Is it possible to strip out the comments when importing the JSON file somehow? I tried to find a JS library or something that would do that, but everything I found is server-side, and I need everything to run client-side.
I'm also not super great with Javascript, so it's possible I'm missing something obvious.
I really appreciate any help you can give!
You can remove all the comments before trying to parse it.
You won't be able to use $.getJSON(), since that tries to parse the JSON itself. Use $.get(), remove the comment and parse it.
$.get('file.json', function(commented_json) {
json = JSON.parse(commented_json.replace(/\/\/.*/g, ''));
// do things
}, "text");
Note that this won't work properly if any of the strings in the JSON contain //. That would require using a real JavaScript parser so it can distinguish the context.
I need all your wisdom today.
So I work on a big legacy project at my company and I have to come up with a solution to share constantes between our back-end in PHP 5 (MVC architecture, no framework) and our front-end with JS (angularJS).
In our backend, we have classes that manage our entities, in which we define constantes we work with. These are constantes like char that we use to refer to different possible values of a field.
class Task {
const STATUS_TODO = 'T';
const STATUS_DONE = 'D';
}
So when we need to make a condition on these constants, we do like so :
if ( $variable === Entity::STATUS_TODO ) { //do something }
But we don't have such management in our front-end, so you often find conditions like :
if ( variable === 'T' ) { //do something }
Which is a terrible thing to do, we all know it.
The point would be to share constantes between the back and the front, so that if we need to change something or add a new constantes, we just have to do it in one place.
I know this is a pretty common problem in web development, and I was wondering how you guys would advise to solve it.
Thanks for your time, have a great day
If possible, collect your constants within special (abstract) classes within a central directory like app/Constants in PHP and src/constants in JS. It is then possible (though I never did that on my own) to create an update-script that will parse the constants from one project and sync them to the other. Both languages can be generated pretty easy so you can even approach a bi-directional solution.
Finally you could set up CI/GitHooks to execute the sync on every commit/push/merge.
In the past I ended up with copying the constants from the PHP project to the JS-Client and then re-format them for JS via RegEx.
I've done some looking around on the site and every time I pull up a solution to this problem, one of the requirements is to have a naming convention and a list of every image to pull from the directory (example: image1.jpg, image2.jpg, etc.) All of the file names are different and there are thousands of them to pick from (so listing each one as a random opportunity in an array is not going to work).
I typically use CMS services and I'm writing this webpage from scratch in Notepad in an attempt to better my coding skills... and I'm not sure where to begin. I'm decent with HTML and CSS, but j Query and JavaScript are not my friends haha.
Thank you for any help! (Even if it's just pointing me to a tutorial or a solution I could not find!!!)
Are all file names image1 image2 image3 etc? Then you could try to generate a random number, create a new img element and have it's source pointing to image+randomnumber.jpg and append it to the DOM
One of the main problems your facing here is about your thinking when it comes to how content is delivered, in a standalone static website you do not have access to the file system. This means that if we want to query things outside of the browsers context we are not allowed, obviously without being able to access directories we can not generate a list of file names which can be loaded.
If your wondering why we can't access the file system directly from say the JavaScript it's because of the sandbox that most modern browsers live in, otherwise people could attack your native directories from the front end languages. Your question is interesting as electron removes this sandboxing in a sophisticated esk manner, which is necessary as it's used for building desktop apps with chromium.
These days the most obvious solution would be to use some form of back end language and to create a web server that has direct access to the native directories around it. Node, PhP, GoLang and many other populatr backend languages can parse a directory of files and then interpolate those into the frontend code which is the most common method.
The other popular method at the moment is to create API's which is just a fancy web server with a queryable end point that then executes code against our web server and provides back a list of such items. You could then for instance take the items and then print those out using javascript.
Reference directories method in php:
http://php.net/manual/en/ref.dir.php
List contents of directory in nodejs:
https://code-maven.com/list-content-of-directory-with-nodejs
The best place to really start with the easiest route to understand more would be to start a backend language in either node or php, with php being the simpler of the two.
https://www.w3schools.com/php/
First you need to get your file list from server side. then you can use a code like following:
var imageList = //your image list as an array of urls;
var imageNumber = Math.random() * imageList.length; //gives you a random number in the range of imageList's size
var imageToLoad = new Image();
imageToLoad.addEventListener("load", function(){
console.log( "image is loading" );
$('#my-container').append(this); //in this case this will return image dom
});
imageToLoad.src = imageList[imageNumber];
this will add image to a container with id 'my-container' its just an example you can do anything you want using 'this'
So after much help and guidance from the community, I have figured out the answer! To clarify my process in extreme detail, here is what I did to achieve the desired outcome:
Create the page as a .php file instead of a .html file (in my case, index.php). If you are using notepad to create the file, make sure you change the file extension to .php, the encoding to UTF-8, and save file type as "All Files". As I understand it, PHP can pick the file at random but cannot pass this info to a static HTML page.
Place this block of code into the webpage where the image should show. Currently, it is set up to reference a folder named, "images" out of the root directory (aka mysite.com/images/). This can be changed by modifying the text between the apostrophes after $imagesDir. All other html markup on the page will work correctly if it is outside of the php code block.
Code Block:
<?php
$imagesDir = 'images/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)];
echo "<img src='$randomImage'>";
?>
Thank you #bardizba for the code! Although there may be less resource intensive ways to write this, my situation was a bit different because the file names in the directory did not follow a naming convention and there was a mix of file types (jpg, gif, etc.)
Thanks again to everyone that helped me out!
Firstly, thanks for taking time to view my post. I am working on a project with a few people, and we basically have a webpage, and once you log in, it displays all the data from a mysql database which has 6 tables, 3 of which have data in them. We figured out that in order for us to go about this, we need to transfer data by exporting the data into JSON file(s), then from there load the JSON files into java script so it can communicate with the web server. We were wondering what would be the best way to go about this. One way we found out is to reference the JSON ddata as variables and just list everything out, but several of our files have loads and loads of data. Would there be an easier approach?
This would be the first time we are doing something like this, so we are learning and appreciate your feedback!!
If you're using some kind of AJAX library, you can easily request the .json file from the browser.
For example with jQuery:
$.post("ourJSONFile.json", function( data ) {
..logic to display data..
});
NOTE - The comment about no PHP was not posted while I was writing this. Until I know why there can be no PHP, I'm just going to leave this answer here.
I think you're going at this in the wrong way. There is no need for JSON here, just query your database for the information.
The overview of what you need to do is (in PHP or the language you use to talk with your server) you need to
connect to the database
query database for information (query in your case, more or less means get the information)
do something with the returned information (such as echoing it in PHP so it will go to the user)
Now, it doesn't look like there is much effort place for getting this done, only planning. So, I'll just show you a few links to read up. (Which is also why people has devoted your question, Stackoverflow doesn't like asking question with no effort to research answers)
I'd use php.net for looking up methods, such as the mysqli_query method. This is very useful for learning small but important things about the method, like what it returns when an error occurs.
http://php.net/manual/en/mysqli.query.php
Taking a quick look through this guide, I think it should suffice. Besides syntax and such, some other important points are use MySQLI (when using PHP 5 or higher) and use prepared statements.
http://www.pontikis.net/blog/how-to-use-php-improved-mysqli-extension-and-why-you-should
The use of prepared statements is to protect your queries from injections. w3schools gives a good explanation about this # http://www.w3schools.com/sql/sql_injection.asp
MySQLI is MySQL Improved, it is more secured and supported. MySQL has been deprecated since PHP 5, and php.net pages on a MySql method will actually say this at the very top.
Finally, Andrew mentioned AJAX. AJAX is (for example) a way of doing things that would normally require reloading the page, without reloading the page. There is more to that, and I would recommand looking into it once you get use to the languages you are using.
Note, AJAX does not require libraries to use, it can be done with pure javascript. Libraries simply (as seen around) simplify AJAX a lot.
I am currently working on the translation of a website.
To perform this translation easily, I created a .csv file containing the matches between the two languages (japanese->english).
Then, this file is parsed with PHP, and ob_start() is called on the page in order to replace wanted strings.
Here is the script :
function lang_modify($buffer){
require('get_messages.php');
for($i=0; $i<count($messages); $i++){
$buffer = str_replace($messages[$i][0], $messages[$i][1], $buffer);
}
return $buffer;
}
$buffer = ob_start('lang_modify');
This script works perfectly on php/html files. However, ob_start does not read javascript files so I was wondering if someone knows a way to include javascript files into the output buffer so that the ob_start() function will replace the words found in javascript as well.
Someone adviced me to do search something with the AddFile statement (.htaccess), but I don't know at all how could I use this to do what I want.
Does anyone have a clue ?
What you are facing here, is a Separation of Concerns issue.
Your translation is generated from PHP.
And yet, your javascript displays and (sometimes) generates those messages.
How do i fix this?
1) Make sure your translations comes from one single source, ideally from PHP
2) Use an i18n js library to process your translations. I suggest: https://airbnb.github.io/polyglot.js/
3) If you are using Polyglot, make sure that your PHP translations are being generated into a js file, which is then loaded based on localisation.
Polygot will translate your default messages into internationalized ones.
In short:
Enable Modularity - Administer(CRUD) all your translations in PHP. Storing them in a database
would be ideal
Decouple JS from translation - Polygot will only provide the translated messages to your views(HTML).