Laravel string localization and AngularJS - javascript

So recently i started to convert my jQuery stuff to AngularJS, but there was a solution what i did not think about.
Not all my pages will use Angular, and i am using Laravel's built in localization.
So the views used by Angular are just plain html, no php or blade included.
So i do not really want to mix the 2 in a view.
Where i use blade i use the built in function example: {{ trans('user.first_name') }}
But since i don't want to mix, and my AngularJS views are pure html, i do not want to use it this way <?php echo trans('user.first_name') ?> in my Angular view.
So i was thinking to include Angular localization for AngularJS, but maintaining 2 different localization structure will be a pain and building a good logic for it is another pain.
So anybody with a solution? currently i am clueless. Because for example with jQuery i did not had to worry about this, because it was just dom manipulation, but now its is more complex

I have developed a package that create a JavaScript file from all Laravel's messages. I think you could use it to have access directly in Laravel.
Basically, after installing the package and running the bundled command you will have a global object: windows.Lang. From there you can do different basic operations such as:
Get a localized message
var message = Lang.get('messages.first_name');
Get a localized message with replacements
var message = Lang.get('messages.welcome', { name: 'Joe' });
Change the current locale (applies to JavaScript)
Lang.setLocale('es');
You can find more information: https://github.com/rmariuzzo/laravel-js-localization

Solved this with a ViewComposer:
app/Http/ViewComposers/TranslateComposer.php
<?php
namespace App\Http\ViewComposers;
use Illuminate\Contracts\View\View;
class TranslateComposer
{
/**
* Bind data to the view.
*
* #param View $view
* #return void
*/
public function compose(View $view)
{
$view->with('jstrans', json_encode(trans('my_locale_resource')));
}
}
app/Providers/AppServiceProvider.php
public function boot()
{
view()->composer(
'*', 'App\Http\ViewComposers\TranslateComposer'
);
}
resources/views/index.blade.php
<script type="text/javascript">
var trans = JSON.parse('{!! $jstrans !!}');
</script>

Related

How to make multiple svelte files json-injectable on call without nodejs?

I have my own custom framework (not using server-side Javascript) that I used for years, and previously I used .html as template for multiple page application.
So for example if I create a file views/foo/bar.html like this:
<script src='list.js'></script>
<script>
let list = [/* user_list */]
</script>
<body onload='renderList('renderTarget')'>
<div id='renderTaraget'></div>
</body>
on the server side, my custom framework would replace the [/* user_list */] section (or any other template keyword) with proper json object, then render the whole template as body of GET /foo/bar, like this on the server side:
func FooBar(c *Ctx) {
// ...
// if GET request
c.RenderHtml(`foo/bar`,M.SX{
`user_list`: userList,
}) // will render views/foo/bar.html
}
How can I achieve similar thing using .svelte, so if I create views/foo/bar.svelte I can return built version and replace the template keyword, and produce similar thing?
Or is it possible for Svelte to produce multiple .htmls on specific directory instead of SPA (and not removing comments), so I won't need nodejs on the server (only need nodejs on development mode).
EDIT: apparently there's svelte-kit static adapter, but we built svelte-mpa specific for this case (it doesn't remove comments).

Take C# const from backend and use it in JS file?

I have one tricky question.
Is there a way to take C# const and use it in .JS script with Jquery ?
This is how const look:
public class UserRoles
{
public const string Read = "Read";
public const string ReadWrite = "ReadWrite";
}
It depends a bit of what you are trying to do with those values.
You could place the values in a js object when your UI initializes (ex: window.YourAppName.Constants.Read = "your C# constant" in Index.html). Then you could load your jquery script and make use of the constant values once the document finished loading.
Alternatively, if you are using MVC, you can make use of tags within your views, and thus have access to C# code (viewmodel, enums, etc.). However, if you have lots of js code then it would be best to keep that in js files and in such a case I would go for the first option.
You can't use Razor in JavaScript files, you would have to have the variable passed to a razor view in the viewbag/data or model.
Then in the shared layout you could create a javascript function that returns this variable, then in your .JS file you could call that function to get the variable as long as it is loaded after.

What is the standard workaround for dynamic js files

Is there a standard workaround for something like this in ASP.NET:
//myinclude.js
$(document).ready(function() {
for(recs=0; recs < {{server-side-value}}; recs++) {
// process records
}
});
Note this is a js file. I know about WinForms ability to insert dynamic quoted scripts into the page. But how about a page's js file that is dependent on server-side values? I know you can use something like:
//myview.cshtml
var instance = new MyObject(<%= ServerSideValue =%>);
and include it on the page to pass it to the js file, but I'm wondering about the architecture of keeping js separate from html code so that an html/css designer can work with the template free of javascript; keeping everything separate. I primarily use MVC now.
What are some of the patterns to deal with this? Is the only solution dynamically inserting js into the actual page or having partial views included separately into the page.? Or is there a way to sprinkle server-side values in separated js? In short, no dynamic js files?
I'm not trying to fix an exact project at this time, I have just been curious about this on past projects.
Thanks...
There are multiple ways to achieve this. One of the ways would be populating your data into a Javascript objects on the HTML page directly.
//myview.cshtml
<script>
var pageData = {
name : '#variable1',
value1: #value1
};
</script>
And, in the javascript file:
//pageUI.js
if (pageData) {
$('#page_tile').html(pageData.name);
}
I am sure you can optimize a whole lot (for example, having a single communication between the server side data and the client side code). At the end of the day, you want to make sure that your javascript code can be resusable.
for example one can do this:
A. have the main .js code read any context-specific parameters from the current window like this (page.js):
!function(window){
var configData = window.MyAppNameConfigData;
// rest app code here..
}(window);
B. the server side script can inject these context-specific data in the page's html like this:
<script>
window.MyAppNameConfigData = {
param1: //..
param2: //..
// etc..
};
</script>
Note if needed make sure that the page.js is enqueued/loaded after the data have been injected/inserted (using a script dependency chain for example)
If it's not "inline" (on the View/Page itself), you could do a Partial View/Page:
Trivial example: _PartialJs.cshtml
$(document).ready(function() {
var foo = "#DateTime.Now.Year";
});
Then in your view:
<script>
#Html.Partial("_PartialJs")
</script>
Renders:
<script>
$(document).ready(function() {
var foo = "2015";
});
</script>
Hth...

How to generate URL for other pages using JavaScript in Symfony2?

Within my Symfony2 application, in order to link to other pages, I've generated the href value using the path Twig function.
I maybe wrong but I think I previously read about a JavaScript equivalent but can't seem to find it now. I am generating some html using JavaScript and want to know if its possible to generate the href values to other pages within the application using purely JavaScript.
Appreciate any advice.
You are probably looking for this bundle: https://github.com/FriendsOfSymfony/FOSJsRoutingBundle
Then you can do this kind of stuff in javascript:
Routing.generate('my_route', {"my":"param"});
I would recommend using FosJsRoutingBundle.
Lets assume an action of controller:
/**
* #Route("/indx/", options={"expose"=true}, name="indexRoute")
* #Template()
*
* #return array
*/
public function indexAction()
{
(...)
}
options={"expose"=true} is what is important here.
Now js equivalent of path call is just:
Routing.generate('indexRoute');

ActiveCollab - How to make an ajax call from a custom module on page load

I'm trying to initiate an ajax call on project brief page by adding a javascript file.I need to display some extra information along with existing project brief information. I included a javascript file in a custom module and followed the procedure explained below. Can you correct me If I'm missing anything here.
I used $.ajax({}) to call the ajax request and my code is like this
$.ajax(
{
type: "post",
url: "index.php?path_info=projectfieldsextra",
'data' : { 'client_value' : 178},
success: function(el)
{
alert(el);
return false;
//$("#project").html(el);
}
});
In controller I created a function get_project_information() and in module definition class I created a route like this
Router::map('projectfieldsextra', 'projectfieldsextra', array('controller' => 'project_fields', 'action' => 'get_project_information'));
But while makinf call , it is giving me an error like this -
Call to a member function isInlineCall() on a non-object in /opt/lampp/htdocs/activecollab/activecollab/4.0.13/angie/frameworks/environment/controllers/FwApplicationController.class.php on line 211
Could anyone help me out in this ?
Thanks in advance
Jayesh
My best guess is that your custom controller (ProjectFieldsController) is not properly set up (it is not properly accepting construction parameters and transferring them to the parent class). If you are overriding controller's constructor, you should do it like this:
/**
* Controller constructor
*
* #param Request $parent
* #param mixed $context
*/
function __construct($parent, $context = null) {
parent::__construct($parent, $context);
// Your code
}
Note that there are other problems with your code, but they are not part of the question, so I will mention them just briefly:
Don't hack the system module. That's a recipe for upgrade problems. Write your own module that hooks into the system via supported events instead.
System convention is to use underscore notation for various system names, including route names. show_project_info is much more readable than showprojectinfo. This is not an error, but you will get along with the framework much easier if you follow the existing naming conventions.

Categories

Resources