问题
I'm trying to learn AngularJS and DjangoCMS so I created a new project using them together.
Status
By default, DjangoCMS uses the first URL segment to determine the language of the site (/en/, /fr/). Every URL that doesn't contain a language segment will get redirected to /en/ by default.
That means, all my AngularJS ajax calls need to be addressed to either /en/api/ or /fr/api/.
Questions
I'd like to use this first segment to determine the language in Angular for internationalization.
And also set that first segment globally to my AngularJS app so I don't need to specify it on each ajax call.
Probable Solution
One solution I found is to use a different template for each language on Django side.
- The english template would have
<base href="/en/">
in the<head>
tag. - The french template would have
<base href="/fr/">
in the<head>
tag and I could either use a pre-bundled rule set or simply add the local script to the script list (https://docs.angularjs.org/guide/i18n).
I guess that would work for more languages too, but that means I have to create a specific template and code for each language.
Best solution ?
I think the best would be to have a logic defined in the Angular app to load the language script depending on the first url segment, and determine that first segment globally in the app. We would avoid having to code things for each language. Is that solution possible ? I searched on setting a base url dynamically on Angular, but I didn't find any interesting results.
I'm not sure that question should be on StackOverflow, but I don't really know about other stack exchange forums.
Thanks !
回答1:
I would do something like this:
- Load i18n template tags:
{% load i18n %}
And set<base href="">
like this:{% get_current_language as LANGUAGE_CODE %} <base href="/{{ LANGUAGE_CODE }}/" />
- When You have base set like above, You can use $provide in to get href value and expose it to services and directives. For example:
angular.module("myapp.services", []) .config(["$provide", function ($provide) { $provide.value("base", $("base").attr("href")); }]);
And inject it to a service which makes ajax calls:angular.module("myapp.services").factory("myService", ["base", function (base) { var uri = base + "api/some_url"; ...
来源:https://stackoverflow.com/questions/35512561/how-to-deal-with-djangocms-i18n-urls-en-my-page-fr-my-page-and-angularjs