Passing Variables to Nunjucks to be used in React - reactjs

Using React, Node, and Express, with a single Nunjucks page for a template, I'm trying to pass a jwt-csrf token from my express server to the Nunjucks page as a javascript variable to be used in the React front-end (which will create post requests with the token).
This is the code in the njk template:
<html lang="en">
<head>
{% include "partials/head.njk" %}
<title>{{appname}}</title>
</head>
<body>
<div id="app"/>
<script src="/bundle.js" type="text/javascript"></script>
</body>
</html>
I had the idea of adding an additional script tag with a global variable, something like like:
<script>window.token = {{token}}</script>
but the {{ and }} get interpreted as javascript rather than as a nunjucks variable. How do I use nunjucks inside of Javscript?
Also, please let me know if what I'm doing is super not-secure, heh.

Related

There is no result with react

This is my first react code to try react work in my laptop but it does not work
As you can see in the picture, the shadow ends before . The shadow must be covering all script tags. I do not know why!
<!DOCTYPE html>
<html>
<head>
<script src="js/react.js"></script>
<script src="js/react-dom.js"></script>
<script src="js/browser.js"></script>
</head>
<body>
<div id = "dome"></div>
<script type='text/jsx'>
ReactDOM.render(<h1>Hello React </h1>,document.getElementById("dome");
</script>
</body>
</html>
JSX is not valid javascript, so it has to be transpiled first. this is why you get the error there. The source you mentioned is somewhat outdated, and is not the origin actually.
Just go with the actual tutorial here:
https://reactjs.org/tutorial/tutorial.html
Your code have a syntax error, bracket of render function is not closed.
ReactDOM.render(<h1>Hello React </h1>,document.getElementById("dome");
Use this:
ReactDOM.render(<h1>Hello React </h1>,document.getElementById("dome"));
Edit: If you want use JSX, you should use text/babel in script type and be sure to import browser.js file.
<script type='text/babel'>
ReactDOM.render(<h1>Hello React </h1>, document.getElementById("dome"));
</script>

How to use AngularJS in jsf page

I want to learn AngularJS to use in JSF pages. This is purely learning purpose.
I tried simply add AngularJS code inside the jsf. But seems it doesn't identify the AngularJS code. it simply out put the same My first expression: {{ 5 + 5 }} in the browser.
my jsf page
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<body>
<div ng-app="hi" >
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>
Can anyone help me how to get the output of the AngularJS expression within the jsf page? or show me some direction
UPDATE
My Actual intention is to get some json from Managebean or from another jsf page and populate here. but for that as testing I tried to create a dummy json structure. but still jsf doesn't identify AngularJS component. It's simply print
My first expression: {{ 5 + 5 }}
Browser console prints MyFirstAng.xhtml:24 Uncaught TypeError: app.conntroller is not a function
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myAPP" ng-controller="customerctrl">
<p>My first expression: {{ 5 + 5 }}</p>
<!-- <ul>
<li ng-repeat="x in myData">
{{x.Name + ', ' + x.Age}}
</li>
</ul>
-->
</div>
</body>
<SCRIPT type="text/javascript">
var app = angular.module('myAPP',[]);
app.conntroller('customerctrl', function($scope){
// $scope.myData=[{Name:'jani',Age:'32'}];
});
</SCRIPT>
</html>
Ok, I found the issue. It was a typo in the app.controller. I had type additional "n". it worked. Thanks for all so far guiding me to spot the issue. I thought I am missing to include some AngularJS library or something.
In order for angular to initialize ng-app="hi" there needs to exist a module with that name. Otherwise you should be seeing an exception thrown in browser dev tools console. Please note console errors when developing javascript apps
Either include a module with that name or remove the name from the attribute and just use ng-app
Either paste this
var app = angular.module('hi',[]);
in your script or make the ng-app="" ... Your choice.
If you specify anything in the ng-app then you have to make a module as given above by me. Otherwise just dont specify anything in the ng-app i.e. ng-app="".
At a later stage when you want to make a controller then you can make a module.. For now its best left empty.

Load only body on page change

On my website i'm displaying the same header on each page and I wanted to know if there's an AngularJS / jQuery or simple JS solution to load only the content of the body and not the header on page change.
<html ng-app="headerApp" ng-controller="HeaderCtrl">
<head>
<!-- here I load my JS and css ... -->
<div ng-include="'templates/Header.tpl.html'"></div>
</head>
<body>
<div ng-include="'templates/IndexBody.tpl.html'"></div>
</body>
<footer><div ng-include="'templates/Footer.tpl.html'"></div> </footer>
</html>
So my HTML looks like this I have separate template for each parts. But for now I create a html file for each pages. So I think there's a way to change the ng-include in the body.
Thanks for your help !
This is kind of the idea behind single page applications. Angular provides a built-in router that does this for you, and there is also the popular ui-router plugin.
You would change your view to:
<html ng-app="headerApp">
<head ng-controller="HeaderCtrl">
<div ng-include="'templates/Header.tpl.html'"></div>
</head>
<body>
<div ng-view></div>
</body>
<footer><div ng-include="'templates/Footer.tpl.html'"></div> </footer>
</html>
and configure the router in app.js:
angular.module('headerApp', ['ngRoute']).config(function($routeProvider){
$routeProvider.when('/', {
templateUrl: 'templates/IndexBody.tpl.html',
controller: 'IndexBodyCtrl'
});
});
Note that you will need to include angular-route.js in your index.html. More reading here: https://docs.angularjs.org/api/ngRoute
If it's an Angular app would you not use ng-view? Everything outside the view is the template and static as such. If you aren't building a spa then Angular probably isn't the best approach.
If it's Jquery then you could just do:
$("article").load('templatefiletoload.html');
beware that loading in your content like this is poor from an SEO point of view. Use server side includes if possible

Serving default index.html page when using Angular HTML5mode and Servicestack on the backend

I am new to ServiceStack and Angular. Apologies if this is verbose.
with reference to Html5 pushstate Urls on ServiceStack
I would like to be able to have my api service served up from the root. ie http://mydomain.com/
If a user browses the route, I would like to serve up a default html page that bootstraps my angular app.
In the the app itself if angular calls mydomain.com/customer/{id} json should be served but if this is browsed directly it should serve the default html page and keep the url but the route in the service method does not need to be called. as this will be resolved by angular which will call the customer service itself for a json result.
There are probably a few different ways to make this work, as long as you don't need to support html5mode urls. I have hope that I'll be able to leverage this code to eventually support html5mode, but at the moment, I've resigned myself to hash based URLs.
Given urls like: http://example.com/ or http://example.com/#/customer/{id}, here's how to bootstap an angularjs single page app on a self-hosted servicestack project from the root of the domain.
To enable the markdown razor engine, add this to your AppHost config (not absolutely necessary, but my preference over the default razor engine):
Plugins.Add(new RazorFormat());
Place a file, default.md, in the root of your project, and ensure it's properties are "content/copy when newer". Put whatever content you want in there. The important thing is to assign the template file. (If you're using the default razor engine, an equivalent default.cshtml file should also work, but I've never tried it. ) The template file is what will bootstrap your angularjs app. This is what I have in my default.md:
#template "Views\Shared\_Layout.shtml"
# This file only exists in order to trigger the load of the template file,
# which bootstraps the angular.js app
# The content of this file is not rendered by the template.
My _Layout.shtml file looks like this (omitting irrelevant details). Note ng-app in the html tag, and the ng-view div in the body. Also note that I don't include <!--#Body--> in the file. I'm not using server side templates for this project.
<!DOCTYPE html>
<html lang="en" ng-app="MyApp">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="Content/css/app-specific.css"/>
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<!-- Navbar goes here -->
<div class="container">
<header id="header">
<!-- Header goes here -->
</header>
<div ng-view></div>
<hr>
<footer id="footer">
<!-- Footer goes here -->
</footer>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="/Scripts/app-specific/app.js?3ba152" type="text/javascript"></script>
<script src="/Scripts/app-specific/app-services.js?3ba152" type="text/javascript"></script>
<script src="/Scripts/app-specific/app-controllers.js?3ba152" type="text/javascript"></script>
</body>
</html>

Including javascript files with templates

I am using AppEngine with the webapp framework (python). In my script I am generating javascript code dynamically with Django, for example:
python controller file
template_values = {
'page': '1',
}
path = os.path.join(os.path.dirname(__file__), "../views/index.html")
self.response.out.write(template.render(path, template_values))
index.html file
<html>
<head>
...
<script>
{% if page %}
alert("test");
{% endif %}
</script>
</head>
<body>
...
</body>
</html>
Now, instead of using inline <script> tags I would like to use the <link> tags with a reference to a JS file containing the script. However, I can't quite understand I can do that using the templates engine. If I include a JS file (dynamically) it would somehow have to know the value of "page", but "page" is known in the scope of index.html only.
Any ideas?
Thanks,
Joel
If you want dynamically generate your javascript code in your html,
you can write the code inside python code
page = 0
template_values = {
'js_code': 'alert("test:'+str(page)+'")',
}
path = os.path.join(os.path.dirname(__file__), "../views/index.html")
self.response.out.write(template.render(path, template_values))
in index.html
<script>
{{js_code}}
</script>
If you want to generate a js file dynamically, you can try to pretend there is a js file,
and generate its content.
class JSHandler(BaseHandler):
def get(self):
page= str(self.request.get("page"))
js_code ='alert("page:'+page+'");'
self.response.out.write(js_code)
def main():
application = webapp.WSGIApplication([
('/code.js', JSHandler),
], debug=True)
wsgiref.handlers.CGIHandler().run(application)
Then you can write this code in your html
<script type="text/javascript" src="/code.js?page={{page}}">></script>
You are either over-complicating a simple situation, or you haven't explained your problem clearly.
If you want to include an externally-located JavaScript file, you would use a <script> tag, not <link>.
If you have template code like this:
<html>
<head>
{% if page %}
<script type="text/javascript" src="/js/foo.js"></script>
{% endif %}
</head>
...
</html>
and page is not None, the template will render the following HTML to the browser:
<html>
<head>
<script type="text/javascript" src="/js/foo.js"></script>
</head>
...
</html>
and the browser will try to load the resource pointed to by the <script> tag. The browser has no knowledge of how that tag got into the HTML that it loaded.

Resources