I am trying to set up a Shop page for my website. I have a navigation bar with 7 items. Each item works. They all work via a RestFUL API (Node server, routes, and controllers...). So I have it set up exactly the same for all pages. But for the shop page it won't work, not sure why. Thanks for all input.
Route
`
router.post('/addshopitem', encodedParser, function(req, res) {
console.log("okay step 2");
const name = req.body.name;
const desc = req.body.desc;
const price = req.body.price;
const stock = req.body.stock;
const createdby = req.body.createdby;
console.log("okay step 2 almost");
ShopController.add_item(req,res,name,desc,price,stock,createdby);
console.log("okay step 2 done");
});
Controller
exports.add_item = (req, res, name, desc, price, stock, createdby) => {
const Item = require('../models/item');
const item = new Item(1, name, desc, price, stock, createdby);
const response = item.save();
if (response) {
res.render('shopitemadded');
} else {
res.render('error');
}
}
NAV-Item
<div class='dropdown'>
<button class='dropbtn' id='shop' onclick="window.location.href='/shop';">Shop</button>
<div class='dropdown-content'></div>
</div>
`
Shop.ejs (View)
`
<body>
<div class='nav-div'>
<%- include('./partials/nav.ejs') %>
</div>
<div class='content' id='content-one'>
<div class="grid">
<%- include('./partials/item.ejs') %>
</div>
</div>
<div class='content' id='content-two'>
</div>
<div class='content' id='content-three'>
</div>
</body>
`
Item.ejs (Partial View Element)
`
<% items.forEach(function(item) { %>
<div class="card"><img class="card__img" src="" alt="Canyons" />
<div class="card__content">
<h1 class="card__header"><%=item.name%></h1>
<p class="card__text"><%=item.desc%></p>
<form action="/shop/addtobasket" method="post">
<input type="text" name="iditem" value="2" style="display: none;">
<label for="amount">2
<input type="text" name="amount" value="3">
</label>
<p>Anzahl an Lager: <%=item.stock%></p>
<p>Stückpreis: <%=item.price%></p>
<input class="card__btn" type="submit" name="submit" value="Dem Warenkorb hinzufügen">
</form>
</div>
</div>
<% })%>
`
I am trying to set up a shop page. I did it the exact same way as all the other views (with a route and a controller). Only thing different: The ejs View has a partial (item.ejs) with a for each inside. Maybe I messed something up in there. Not sure.
I've manage to generate the List.cshtml shape for rendering the list of content items, in my case this content item has a Title(text), Description(text), hyperlink and Image. So I want all this part to be rendered base on my expected layout, all part such as Title, Description and hyperlink is okay but when I tried to render this Image part there is no path of the image. where and how do I get this piece of information as long this image can be rendered in the view.
Expected layout.
Orchard default layout
Code for List.cshtml:
#{
var contentItems = new List<Object>();
if (Model.Items != null)
{
contentItems = Model.Items;
}
}
<div class="main-post">
<div class="container">
#foreach (var mainContentItem in contentItems)
{
var targetContentItem = (Orchard.DisplayManagement.Shapes.Shape)mainContentItem;
var listOfShapes = targetContentItem.Items.ToList();
var title = listOfShapes[0];
var desc = listOfShapes[1];
var mediaLib = listOfShapes[2];
var actionLink = listOfShapes[3];
<div class="clearfix hidden-xs" style="height:40px;"></div> <!-- spacer -->
<row>
<div class="col-sm-3 hidden-xs">
<figure>
#mediaLib.Item
#*
<img src="#mediaLib.Item" class="animation animated animation-fade-in-left" data-animation="animation-fade-in-left">
*#
</figure>
</div>
<div class="col-sm-7">
<div class="col-text">
<div class="post-heading-left">
<h2>#title.Item</h2>
</div>
<p>#desc.Item</p>
<button onclick="window.open('#actionLink.Item')" type="button" class="btn btn-primary">View App</button>
</div>
</div>
</row>
}
</div>
</div>
I have some code that I wrote to essentially handle a login with a back end API supporting it.
My problem is that after the form POSTS the data to the server (and it is accepted), the index page (which is the same place this form is located on) still shows the login form instead of the different if statement I have in the file.
BUT, if I refresh the page, the correct part of the if statement displays. I have been at this all day, and I need a fresh pair of eyes to look over it and see what I'm doing something wrong:
define([
'lodash',
'log4js',
'path',
'when',
'common/lang/Disposable',
'common/commands/CommandHandler',
'common-node/network/http/Verb',
'common-node/network/server/endpoints/html/PageContainer',
'common-node/network/server/endpoints/html/PageEndpoint',
'common-node/network/server/ServerDefinition',
'common-node/network/server/ServerFactory.instance',
], function(_, log4js, path, when, Disposable, CommandHandler, Verb, PageContainer, PageEndpoint, ServerDefinition, serverFactory) {
//'use strict';
var m;
var session = require('client-sessions');
session({
cookieName: 'GBE_OWNED',
secret: '12112asdfasdf',
duration: 30 * 60 * 1000,
activeDuration: 5 * 60 * 1000,
});
var logger = log4js.getLogger('server/GbeSeasonalsWebServer');
var GbeSeasonalsWebServer = Disposable.extend({
init: function() {
},
start: function(configuration) {
var port = getContainerPort(configuration.container);
var state = false;
var indexHandler = new CommandHandler.fromFunction(function(input) {
console.log(input || { });
if(input.logout == ''){
session.qry = '';
session.Name = '';
return {
name: '',
currentState: false,
reloadLogout: true
};
}
if(typeof session.qry === 'undefined' || session.qry === null || session.qry === ''){
//the user isn't logged in
state = false;
}
else{
console.log(session.qry);
state = true;
}
return {
name: session.Name,
currentState: state
};
});
var loginHandler = new CommandHandler.fromFunction(function(input) {
var userName = input.username;
var userPass = input.password;
var rememberMe = input.remember;
var retro = false;
var iResponse;
var productIDs = 'USC_SEASONAL_CB,USC_SEASONAL_CB'; // this will be changed when jose gets back to me with the specifics
var https = require('https');
var callback = function(response){
var str = '';
response.on('data', function(chunk){
str += chunk;
});
response.on('end', function () {
try{
var DOMParser = require('xmldom').DOMParser;
}catch(err){
return {error: "There appeared to be an error. Please try again."};
}
var doc = new DOMParser().parseFromString(str,'text/xml');
var isSuccessful = doc.firstChild.attributes[1].nodeValue;
if(isSuccessful == 'True'){
retro = true;
//I need to set a session here
console.log("The account was logged in successfully.");
session.qry = '?username=' + userName + '&password=' + userPass + '&productids=' + productIDs;
//console.log(session.username);
if(typeof str === 'undefined' || str === null){return {error: "There appeared to be an error. Please try again."};}
session.Name = doc.firstChild.attributes[4].nodeValue + ' ' + doc.firstChild.attributes[5].nodeValue;
var state = true;
iResponse = function (){
return {
name: session.Name,
currentState: true,
reload: true,
};
};
}
else{
iResponse = function (){
return {
error: "There appeared to be a problem while trying to log you in.",
name: "WHATTHEHELL",
state: false
};
};
}
return iResponse;
});
response.on('error', function (e) {
console.log(e);
});
};
return https.request('https://secure.barchart.com/banker/getuserpermissions.ashx?username=' + userName + '&password=' + userPass + '&productids=' + productIDs, callback).end();
});
var definition = ServerDefinition
.withContainer(
new PageContainer(port, '/')
.addEndpoint(new PageEndpoint(Verb.GET, '', 'index', indexHandler))
.addEndpoint(new PageEndpoint(Verb.POST, '', 'index', loginHandler))
.addEndpoint(new PageEndpoint(Verb.GET, '/index', 'index', indexHandler))
.addEndpoint(new PageEndpoint(Verb.POST, '/index', 'index', loginHandler))
.addEndpoint(new PageEndpoint(Verb.GET, '/signup', 'signup'))
.addEndpoint(new PageEndpoint(Verb.POST, '/signup', 'signup'))
.addEndpoint(new PageEndpoint(Verb.GET, '/more', 'more'))
);
definition.withTemplatePath(path.join(configuration.server.path, configuration.container.http.templatePath));
_.forEach(configuration.container.http.staticPaths, function(filePath, serverPath) {
definition.withStaticPath(path.join(configuration.server.path, filePath), serverPath);
});
return when.try(function() {
serverFactory.build(definition);
}).then(function() {
return true;
});
},
_onDispose: function() {
logger.warn('GBE Seasonals web server is being disposed');
},
toString: function() {
return '[GbeSeasonalsWebServer]';
}
});
function getContainerPort(containerConfiguration) {
var port = parseInt(process.env.PORT);
if (_.isNaN(port)) {
port = null;
}
return port || containerConfiguration.port || 8080;
}
return GbeSeasonalsWebServer;
});
And the index page:
<!DOCTYPE html>
<html lang="en">
<head>
<title>GBE SEASONALS STAGING SITE © Barchart™</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Custom theme -->
<link rel="stylesheet" type="text/css" href="static/css/custom.css">
</head>
<body>
<script type="text/javascript">
var c = '{{name}}';
var state = '{{currentState}}';
{{#if reload}}
window.location = window.location.href;
{{/if}}
{{#if reloadLogout}}
window.location = window.location.href.split("?")[0];
{{/if}}
if(state==''){window.location = window.location.href; }
</script>
<div class="container">
<div class = "row">
<div class="col-md-10 col-md-offset-1">
<a href="index">
<img style = "vertical-align:middle;display:inline-block" src="http://www.gbemembers.com/images/GBE_Logo_horiz.png" class="img-responsive">
<p style="color:white;margin-top:50px;margin-right:20px;font-size:20px" class="pull-right">Seasonals</p>
</a>
</div>
</div>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading"></div>
<div class="panel-body">
<div class = "row">
{{#if error}}
<div class="alert alert-danger" role="alert">
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span class=""><b>Error:</b></span>
{{error}}
</div>
{{/if}}
{{#if currentState}}
<div class = "col-md-12">
<p class = "pull-right">Welcome back {{name}}! Click here to log out.</p>
</div>
{{else}}
<center>
<div class = "col-md-12">
<form class="form-inline" style = "width:100%;margin:0 auto;" method="post" action = "?"><label>Already a member? Login here: </label>
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3">Email address</label>
<input type="" class="form-control" id="exampleInputEmail3" placeholder="Email" name = "username">
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword3">Password</label>
<input type="password" class="form-control" id="exampleInputPassword3" placeholder="Password" name = "password">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name = "remember"> Remember me
</label>
</div>
<button type="submit" class="btn btn-default">Sign in</button>
<input type = "button" value = "Register" class="btn btn-default">
</form>
<p></p>
</div>
</center>
{{/if}}
</div>
<div class = "row">
<div class = "col-md-12">
<div class="jumbotron">
<h1>Hello, world!</h1>
<p>This is an example of a jumbotron....because you're worth it.</p>
<p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>
</div>
</div>
</div>
<div class = "row">
<div class = "col-md-12">
<p>
Freegan tacos before they sold out, health goth sriracha chartreuse kinfolk jean shorts man braid artisan literally. Brooklyn vice hashtag, meh tumblr kombucha marfa readymade. Ennui cold-pressed distillery freegan. Kale chips tilde +1, mumblecore franzen migas paleo. Offal 3 wolf moon before they sold out, health goth disrupt fixie bitters flannel meditation pop-up flexitarian irony meh. Deep v put a bird on it pork belly cardigan etsy. Lumbersexual literally crucifix slow-carb cardigan.
</p>
</div>
</div>
<div class = "row">
<div class = "col-md-12">
<p>Asymmetrical readymade brooklyn, blue bottle master cleanse disrupt artisan +1 actually affogato roof party DIY polaroid next level retro. Brooklyn poutine vegan bitters you probably haven't heard of them. Celiac helvetica master cleanse williamsburg, synth shabby chic fixie. Viral typewriter cred, roof party kombucha readymade offal shabby chic meggings. Gochujang chillwave VHS food truck. Ennui ugh twee, mumblecore sriracha DIY gastropub hella 3 wolf moon pabst kale chips typewriter trust fund direct trade. Neutra microdosing selfies listicle.</p>
</div>
</div>
<div class = "row">
<div class = "col-md-12">
<p>
Gochujang farm-to-table offal, distillery tofu migas skateboard 90's. Ethical ramps hoodie, YOLO vice before they sold out four loko literally mustache post-ironic. Fixie ennui literally lumbersexual photo booth umami disrupt messenger bag man braid polaroid. Cold-pressed aesthetic marfa, vinyl truffaut squid 3 wolf moon sriracha keytar knausgaard echo park. Chambray leggings microdosing mustache migas. Keytar portland chambray, quinoa ugh farm-to-table mustache cred mixtape craft beer. Thundercats chia keytar beard, drinking vinegar mustache man bun slow-carb wayfarers polaroid lo-fi chicharrones.
</p>
</div>
</div>
<div class = "row">
<div class = "col-md-12">
<p>
Quinoa cred taxidermy, cold-pressed microdosing offal mustache gluten-free small batch tousled twee wayfarers. Wolf williamsburg normcore lo-fi, tilde seitan hammock bushwick DIY organic single-origin coffee quinoa microdosing man braid. Fap small batch PBR&B microdosing, migas pork belly occupy aesthetic pop-up slow-carb 3 wolf moon. Blue bottle XOXO occupy +1, pabst lomo chicharrones ethical heirloom helvetica asymmetrical. Bushwick shabby chic yr kombucha, flannel truffaut raw denim banh mi bitters gluten-free pickled hoodie letterpress sartorial. YOLO whatever tacos meggings venmo, keytar knausgaard mumblecore. Tilde waistcoat offal, locavore cred umami mlkshk vice lomo lo-fi tousled selvage blog tattooed poutine.
</p>
</div>
</div>
<div class = "row">
<div class = "col-md-12">
<button type="button" class="btn btn-primary btn-lg btn-block">Click here to sign up!</button>
</div>
</div>
</div>
<div class = "panel-footer">GBE Seasonal © 2016 Barchart</div>
</div>
</div>
</div>
</div> <!-- /container -->
<!-- Let's load the javascript dendencies now -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script type="text/javascript" src = "http://getbootstrap.com/assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
I believe it is a session issue, but I cannot seem to get around the issue. What's more, I cannot even get the callback function to return the needed data.
I have a named view called myView in which I have two div elements that I want to show conditionally using ng-show based on whether the value of $scope.states['currentState'] is 'A' or 'B'. The value of $scope.states['currentState'] is changed when an anchor tag is clicked which calls the doStuff function on the myController controller.
The issue I am having is when the anchor tag is clicked and the doStuff function is clicked, it shows on the console that the value of $scope.states['currentState'] has been modified, but its not updating the myView named view accordingly.
Following is the code for app.js, myView.html and index.html files. The index.html file is being used as a <div ui-view></div> in an index.ejs file that I am rendering using Express with Node.js.
app.js
var app = angular.module("app", ['ui.router']).
config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
views: {
'': { templateUrl: 'partials/index.html' },
'myView#home': {
templateUrl: 'partials/myView.html',
controller: 'myController'
},
'myOtherView#home': {
templateUrl: 'partials/myOtherView.html',
controller: 'myController'
}
}
});
}])
app.controller("myController", ['$scope', function($scope){
var states = ['A', 'B'];
$scope.states = states;
$scope.states['currentState'] = states['currentState'] || 'A';
$scope.doStuff = function(toState) {
//doing stuff
$scope.states['currentState'] = toState;
console.log($scope.states['currentState']);
};
} ]);
index.html
<div class="main">
<div class="container">
<div class="row margin-bottom-40">
<div class="col-md-12 col-sm-12">
<div class="content-page">
<div class="row">
<div ui-view="myView"></div>
<div ui-view="myOtherView"></div>
</div>
</div>
</div>
</div>
</div>
</div>
myView.html
<div ng-controller='myController'>
<div ng-show="states['currentState'] == 'A'">
//displaying this div if the currentState is A
<a ng-click="doStuff('B')">Do stuff and show B</a>
</div>
<div ng-show="states['currentState'] == 'B'">
//displaying this div if the currentState is B
</div>
</div>
Could somebody help me understand that why am not getting the div with states['currentState'] == 'B' shown, even when I see the value of console.log($scope.states['currentState']) changed from 'A' to 'B' when the doStuff function is called in myController?
Edit:
Here is the demo of the issue I am facing.
Okay So I was mistaken in my comment.
The real issue was that you used {{}} in your ng-show which is not needed as these expect to take angular expressions.Also I would make current state a property of your scope as at the moment you are trying to make it a property of an array inside your scope.
Hope that helps! Below is the modified code for your view:
<div ng-controller='MainCtrl'>
<div ng-show="currentState === 'A'">
<a ng-click="doStuff('B')">Do stuff and show B</a>
</div>
<div ng-show="currentState === 'B'">
<a ng-click="doStuff('A')">Do stuff and show A</a>
</div>
</div>
EDIT: Working plunker http://plnkr.co/edit/1llQMQEdxIwu65MNoorx?p=preview
Im using handlebars in a node aplication, and I have trouble.
This is the template index.html
{{CONTENT}}
This is the code
var fs = require("fs");
var handlebars = require("handlebars");
var data = {
CONTENT: "<b>Hello world!</b>"
};
var templateFile = fs.readFileSync('./index.html', 'utf8');
var template = handlebars.compile( templateFile );
var html = template(data);
The problem is that the tags <B> are escaped to <B>
How can I avoid this?
From handlebarsjs.com :
Handlebars HTML-escapes values returned by a {{expression}}. If you
don't want Handlebars to escape a value, use the "triple-stash".
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{{body}}}
</div>
</div>
with this context:
{
title: "All about <p> Tags",
body: "<p>This is a post about <p> tags</p>"
}
results in:
<div class="entry">
<h1>All About <p> Tags</h1>
<div class="body">
<p>This is a post about <p> tags</p>
</div>
</div>
However from my point of view it may defeat the purpose of having a template separated than you're js file.
If you use precompile then use noEscape option:
handlebars.precompile(content, {noEscape: true})
You'd want to use the 'triple stash' in your template:
{{{CONTENT}}}