how can i use ejs variables from other file - javascript

i am trying to do spa and i am kind of stacking in this code
import AbstractView from "./AbstractView.js";
export default class extends AbstractView {
constructor(params) {
super(params);
this.setTitle("Profile");
}
async getHtml() {
return `
<main>
<center>
<div class="profile-page">
<img src="" alt="astro" style="border-radius: 50%;margin-right: 15px;">
<h1 style="font-size: 20px;"><%= client.user.username %></h1>
<h3>Select server to start managing</h3>
<br>
<button class="button_support">Support</button>
</div>
</center>
</main>
`;
}
}
This is taking from github source and what i am trying to do is i want to show ejs variable in the html and this what happen:
problem
if you have any question about the code ask and a will text you back thank you!

Since I don't see where you are rendering from with ejs, I can't see much;
These are some key things to check:
Make sure the variable in the ejs file matches very well with what you have rendered in the server. It's case sensitive and you should in fact copy and paste. Also, don't keep those variables or const in quotes ", it's also a common mistake;
It will be very helpful if you can share the exact error message you are getting.

Related

How to save image link in when using 'require' to display image in VueJS?

I am trying to create a page where I show Pizza items with their images. The Pizza object is saved in the DB with a field imgUrl. The image is not getting displayed but I see the alt text that I provided but I can see in the console that the image link is correct.
Right now, the imgUrl field in the database has data like ../assets/images/pizza.jpg. Should I instead save require(../assets/images/pizza.jpg) in the db. That looks weird. Here is the code, please look at the mounted method.
<template>
<div>
<div class="class">
<span><h1>All you can eat Menu.</h1></span>
<div class="container">
<div class="box" v-for="item in pizzaList" :key="item.id">
<div>
<img :src="item.imgUrl" alt="Image"/>
<div>
<a class="btn" #mouseenter="$event.currentTarget.style.background = '#EF6B7F'"
#mouseleave="$event.currentTarget.style.background = '#e31837' ">Buy Now</a>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data () {
return {
pizzaList: []
}
},
mounted: function () {
axios.get('http://localhost:8081/api/pizza/all')
.then(response => {
this.pizzaList = response.data;
})
.catch(e => {
console.log(e);
})
}
}
</script>
I have already read
Vue and API: Displaying Image
Image path in Vue JS
How to reference static assets within vue javascript
but what these answers are telling is how to do when we have hardcoded the url, we should encapsulate it with require but they do not tell when we are getting the link from the DB, how do we put require in the html tag.
I hope my question was clear. Please ask for details if you need. thanks
The reason it was not working was because
Webpack's require() needs at least some part of the file path to be completely static and we should "make only part of the path dynamic"
that means you cannot put the entire image path in the DB and in the UI pass it to require and expect it to work
I replaced
<img :src="require(`${item.imgUrl}`)" alt="Image"/>
where item.imgUrl = '../assets/entities/pizza/pizza_1.jpg' (which is the entire image path relative to the component)
by
<img :src="require(`../assets${item.imgUrl}`)" alt="Image"/>
where item.imgUrl = '/entities/pizza/pizza_1.jpg'
This answer mentioned by Michal Levy up in the comments explains all this
https://stackoverflow.com/a/64208406/8147680

Javascript onclick do not execute until click

I am working in Microsoft Framework to create an application customizer which can only contain html code as a string. I created the html I want to render and need to add some functionality to open a link via a javascript method givien by Microsoft Teams. The main problem though is that it fires directly. I usually add an addListener to the method, but since it has to be HTML in a .ts file I cannot do that. So I am wondering except for that method what else would prevent the browser from triggering my openLink function from executing immediately.
I also cannot use React code where it would be as simple as onClick={() => sth(1)}.
My Code:
private _renderTopBar(navData, context) {
const { logoUrl, navigation } = navData;
let logo = logoUrl.replace('-my', '');
function openLink(url) {
console.log('got executed...')
}
return `
<section class="${styles.top}">
<div class="${styles.headerRow}">
<div class="${styles.mainHeader}">
<div class="${styles.logoCell}"><img src="${'https://one365demo.sharepoint.com/:i:/r/Style%20Library/hublogo.png'}" /></div>
<div class="${styles.titleCell}">
Start
</div>
</div>
</section>
`;
}
Any help would be much appreciated. Cheers!

What is an elegant way to initialize multiple react-live components from a static website?

I'm currently creating a react component library that i want to provide as an npm package. I also want to provide a documentation that features fancy live rendering of the available components on e.g. github pages.
For the live editing feature i'm planning to use react-live which provides multiple react components to display a live editor and a preview. See an example from the styled-components docs how this looks like.
The react-live component accepts a string code containing the initial code that should be displayed in the editor and a list of components scope that can be used inside the live editor.
Now i want to use gohugo or a similar static site generator to deploy my documentation. I thought i could maybe provide a <div> inside my static site that has a special class react-live-demo and i will get these containers with document.getElementsByClassName('react-live-demo'), loop over them and render the react-live component into it.
I created a code snippet that shows a little example:
const {LiveProvider, LiveEditor, LiveError, LivePreview} = window['react-live'];
// a random component that i want to render in the live editor
const MyComponent = () => (
<div>
<h1>react live demo</h1>
<p>This is a component from the script tag.</p>
</div>
);
// a wrapper for the react-live editor
const Editor = ({code, scope}) => (
<LiveProvider code={code} scope={scope}>
<div className="live-example row">
<div className="col-xs">
<LiveEditor />
<LiveError />
</div>
<div className="col-xs">
<LivePreview />
</div>
</div>
</LiveProvider>
);
// get all containers that have the initial code as innerHTML
const examples = document.querySelectorAll('script[data-name="react-live"]');
examples.forEach(example => {
// insert a new div before the script tag
const container = document.createElement('div');
example.parentNode.insertBefore(container, example.nextSibling);
// render the editor with the code from the script tag
const code = example.innerHTML.trim();
ReactDOM.render(<Editor code={code} scope={{MyComponent}} />, container);
});
.static-content {
background-color: papayawhip;
}
.live-example {
border: 1px solid orange;
}
.react-live-demo.code {
display: none;
}
.invalid {
color: red;
}
<p class="static-content">HERE IS SOME STATIC HTML CONTENT</p>
<script type="text/html" data-name="react-live">
<div>
<h1>react live demo</h1>
<p>This code is editable.</p>
</div>
</script>
<p class="static-content">SOME MORE STATIC HTML CONTENT</p>
<script type="text/html" data-name="react-live">
<MyComponent />
</script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/flexboxgrid/6.3.1/flexboxgrid.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://unpkg.com/react-live#1.7.0/dist/react-live.min.js"></script>
The question is now:
How do embed the code string into my static site so that i can grab it with my js code and pass it to my react-live component?
I thought about <pre> or something like that. Or should i just embed it as inner html and read that? But then it would be displayed for short when the react component hasn't rendered yet. Or should i use some sort of script tag and make it available as globals? The key goal is to make it as easy as possible to add live editing examples to the documentation without touching any javascript code.
However if i pass something like <MyComponent /> as innerHTML this does of course not work as you can see in the code snippet.
Any best practice for that use case appreciated.
EDIT:
Based on the suggestion of #Daniel Alexandrov i edited the code snippet. The solution now reads the innerHTML of script tags with type="text/html set and creates a <div> container to insert the editor. This seems to work quite well. Any more ideas?
In my opinion the best choice is to use the <script> tag with a custom type attribute. Take a look at the Knockout.js template binding which uses type="text/html or the Angular <script type="text/ng-template">
This way the browser will ignore the script tag completely, because it doesn't know how to interpret it.

Vue js error: Component template should contain exactly one root element

I don't know what the error is, so far I am testing through console log to check for changes after selecting a file (for uploading).
When I run $ npm run watch, i get the following error:
"Webpack is watching the files…
95% emitting
ERROR Failed to compile with 1 errors
19:42:29
error in ./resources/assets/js/components/File.vue
(Emitted value instead of an instance of Error) Vue template syntax
error:
Component template should contain exactly one root element. If you
are using v-if on multiple elements, use v-else-if to chain them
instead.
# ./resources/assets/js/components/AvatarUpload.vue 5:2-181 #
./resources/assets/js/app.js # multi ./resources/assets/js/app.js
./resources/assets/sass/app.scss"
My File.vue is
<template>
<div class="form-group">
<label for="avatar" class="control-label">Avatar</label>
<input type="file" v-on:change="fileChange" id="avatar">
<div class="help-block">
Help block here updated 4 🍸 ...
</div>
</div>
<div class="col-md-6">
<input type="hidden" name="avatar_id">
<img class="avatar" title="Current avatar">
</div>
</template>
<script>
export default{
methods: {
fileChange(){
console.log('Test of file input change')
}
}
}
</script>
Any ideas on how to solve this? What is actually the error?
Note This answer only applies to version 2.x of Vue. Version 3 has lifted this restriction.
You have two root elements in your template.
<div class="form-group">
...
</div>
<div class="col-md-6">
...
</div>
And you need one.
<div>
<div class="form-group">
...
</div>
<div class="col-md-6">
...
</div>
</div>
Essentially in Vue you must have only one root element in your templates.
For a more complete answer: http://www.compulsivecoders.com/tech/vuejs-component-template-should-contain-exactly-one-root-element/
But basically:
Currently, a VueJS template can contain only one root element (because of rendering issue)
In cases you really need to have two root elements because HTML structure does not allow you to create a wrapping parent element, you can use vue-fragment.
To install it:
npm install vue-fragment
To use it:
import Fragment from 'vue-fragment';
Vue.use(Fragment.Plugin);
// or
import { Plugin } from 'vue-fragment';
Vue.use(Plugin);
Then, in your component:
<template>
<fragment>
<tr class="hola">
...
</tr>
<tr class="hello">
...
</tr>
</fragment>
</template>
You need to wrap all the html into one single element.
<template>
<div>
<div class="form-group">
<label for="avatar" class="control-label">Avatar</label>
<input type="file" v-on:change="fileChange" id="avatar">
<div class="help-block">
Help block here updated 4 🍸 ...
</div>
</div>
<div class="col-md-6">
<input type="hidden" name="avatar_id">
<img class="avatar" title="Current avatar">
</div>
</div>
</template>
<script>
export default{
methods: {
fileChange(){
console.log('Test of file input change')
}
}
}
</script>
if, for any reasons, you don't want to add a wrapper (in my first case it was for <tr/> components), you can use a functionnal component.
Instead of having a single components/MyCompo.vue you will have few files in a components/MyCompo folder :
components/MyCompo/index.js
components/MyCompo/File.vue
components/MyCompo/Avatar.vue
With this structure, the way you call your component won't change.
components/MyCompo/index.js file content :
import File from './File';
import Avatar from './Avatar';
const commonSort=(a,b)=>b-a;
export default {
functional: true,
name: 'MyCompo',
props: [ 'someProp', 'plopProp' ],
render(createElement, context) {
return [
createElement( File, { props: Object.assign({light: true, sort: commonSort},context.props) } ),
createElement( Avatar, { props: Object.assign({light: false, sort: commonSort},context.props) } )
];
}
};
And if you have some function or data used in both templates, passed them as properties and that's it !
I let you imagine building list of components and so much features with this pattern.
Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.
The right approach is
<template>
<div> <!-- The root -->
<p></p>
<p></p>
</div>
</template>
The wrong approach
<template> <!-- No root Element -->
<p></p>
<p></p>
</template>
Multi Root Components
The way around to that problem is using functional components, they are components where you have to pass no reactive data means component will not be watching for any data changes as well as not updating it self when something in parent component changes.
As this is a work around it comes with a price, functional components don't have any life cycle hooks passed to it, they are instance less as well you cannot refer to this anymore and everything is passed with context.
Here is how you can create a simple functional component.
Vue.component('my-component', {
// you must set functional as true
functional: true,
// Props are optional
props: {
// ...
},
// To compensate for the lack of an instance,
// we are now provided a 2nd context argument.
render: function (createElement, context) {
// ...
}
})
Now that we have covered functional components in some detail lets cover how to create multi root components, for that I am gonna present you with a generic example.
<template>
<ul>
<NavBarRoutes :routes="persistentNavRoutes"/>
<NavBarRoutes v-if="loggedIn" :routes="loggedInNavRoutes" />
<NavBarRoutes v-else :routes="loggedOutNavRoutes" />
</ul>
</template>
Now if we take a look at NavBarRoutes template
<template>
<li
v-for="route in routes"
:key="route.name"
>
<router-link :to="route">
{{ route.title }}
</router-link>
</li>
</template>
We cant do some thing like this we will be violating single root component restriction
Solution
Make this component functional and use render
{
functional: true,
render(h, { props }) {
return props.routes.map(route =>
<li key={route.name}>
<router-link to={route}>
{route.title}
</router-link>
</li>
)
}
Here you have it you have created a multi root component, Happy coding
Reference for more details visit: https://blog.carbonteq.com/vuejs-create-multi-root-components/
In addition to Bert and blobmaster responses:
If you need to remove the root element from the DOM you can exploit css and use display: value on the root element.
Bit of a misleading error.
What fixed it on my side was the fact that I had an additional </div> without an opening <div>.
I spotted it using Find/Replace on "div" which gave an odd number.
Wrap everything in one div and it will resolve the issue.
For example,
div
----div
----/div>
----div>
----/div>
/div
It is similar concept to React.js
For vue 3 they removed this constraint in template syntax :
<template>
<header>...</header>
<main v-bind="$attrs">...</main>
<footer>...</footer>
</template>
but it's still existing in JSX syntax :
Incorrect ❌
setup(props,{attrs}) {
return ()=>(
<header>...</header>
<main {..attrs}>...</main>
<footer>...</footer>
)
}
Correct ✔
setup(props,{attrs}) {
return ()=>(
<>
<header>...</header>
<main {..attrs}>...</main>
<footer>...</footer>
</>
)
}
I experienced this kind of issue and the issue was fixed by adding a main parent div tag or section if it is a section type of component.
<div class="list-of-friends">
<h3>Hello World</h3>
</div>
I was confused as I knew VueJS should only contain 1 root element and yet I was still getting this same "template syntax error Component template should contain exactly one root element..." error on an extremely simple component. Turns out I had just mispelled </template> as </tempate> and that was giving me this same error in a few files I copied and pasted. In summary, check your syntax for any mispellings in your component.
instead of using this
Vue.component('tabs', {
template: `
<div class="tabs">
<ul>
<li class="is-active"><a>Pictures</a></li>
<li><a>Music</a></li>
<li><a>Videos</a></li>
<li><a>Documents</a></li>
</ul>
</div>
<div class="tabs-content">
<slot></slot>
</div>
`,
});
you should use
Vue.component('tabs', {
template: `
<div>
<div class="tabs">
<ul>
<li class="is-active"><a>Pictures</a></li>
<li><a>Music</a></li>
<li><a>Videos</a></li>
<li><a>Documents</a></li>
</ul>
</div>
<div class="tabs-content">
<slot></slot>
</div>
</div>
`,
});
Just make sure that you have one root div and put everything inside this root
<div class="root">
<!--and put all child here --!>
<div class='child1'></div>
<div class='child2'></div>
</div>
and so on

How to enhance a server side generated page with Aurelia.io?

I'm writing an app with some parts as SPA and some pages generated on server side for SEO. I've chosen Aurelia.io framework and I use enhance method to enable custom elements on my pages. But I can't find the best way to use aurelia specific template directives and interpolation on my server side page. Let's start with an exemple.
All of my pages contains a dynamic header. This header will be a custom element named my-cool-header. This header will load authentified user and display its name, or, if no user is currently authentified, a link to the signin will be displayed. The body of the page will be generated on server side and cached. So, we'll have something like that :
<html>
<body>
<my-cool-header>
<img src="logo.png">
<div
show.bind="user">${user.name}</div>
<div
show.bind="!user">Sign-in</div>
</my-cool-header>
<div>Cachabled content</div>
</body>
</html>
Then, my header will by defined by :
import {UserService} from './user';
import {inject} from 'aurelia-framework';
#inject(UserService)
export class MyCoolHeader {
constructor(userService) {
this.userService = userService;
}
async attached() {
this.user = await this.userService.get();
}
}
With the following template :
<template>
<content></content>
</template>
And this bootstrap script :
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging()
.globalResources('my-cool-header');
aurelia.start().then(a => a.enhance(document.body));
}
In this configuration, the custom element is well loaded and instanciated. But, I can't access the viewModel of the node inside the <content> node. So, all the interpolation (${user.name}) and attributes (show.bind) are ignored. If I include a custom-element in my content template, it will be loaded only if it is declared as global in the bootstrap : the` tag is ignored.
I've found a workaround to be able to change the viewModel after reading the doc by setting a custom viewModel to enhance method and then, injecting it to my custom element class. Something like :
import {MainData} from './main-data';
export function configure(aurelia) {
const mainData = aurelia.container.get(MainData);
aurelia.use
.standardConfiguration()
.developmentLogging()
.globalResources('my-cool-header');
aurelia.start().then(a => a.enhance(mainData, document.body));
}
Custom element:
import {UserService} from './user';
import {inject} from 'aurelia-framework';
import {MainData} from './main-data';
#inject(UserService, MainData)
export class MyCustomElement {
constructor(userService, mainData) {
this.userService = userService;
this.mainData = mainData;
}
async attached() {
this.mainData.user = await this.userService.get();
}
}
And finally, if I change my template like that, it will work :
<html>
<body>
<my-cool-header
user.bind="user">
<img src="logo.png">
<div
show.bind="user">${user.name}</div>
<div
show.bind="!user">Sign-in</div>
</my-cool-header>
<div>Cachabled content</div>
</body>
</html>
I can't believe it is the right way to do because it's ugly and it does not resolve the problem of <require> tag. So my question is : What is the best way to do ?
Thanks to your clues, I found the solution!
Custom element need to construct its own template:
import {processContent, noView} from 'aurelia-framework';
#processContent(function(viewCompiler, viewResources, element, instruction) {
instruction.viewFactory = viewCompiler.compile(`<template>${element.innerHTML}</template>`, viewResources, instruction);
element.innerHTML = '';
return false;
})
#noView
export class MyCustomElement {
attached() {
this.world = 'World!';
this.display = true;
}
}
Then, in my view from server, we can interpolate and require custom elements!
<body>
<my-custom-element>
<require="./other-custom-element"></require>
<p
if.bind="display">Hello ${world}</p>
<other-custom-element></other-custom-element>
</my-custom-element>
</body>
I've wrote a decorator to help creating this kind of enhanced custom elements : https://github.com/hadrienl/aurelia-enhanced-template
Plus de détails en français sur mon blog : https://blog.hadrien.eu/2016/02/04/amelioration-progressive-avec-aurelia-io/
EDIT: <require> is not really working with this solution. I have to dig again :(
Change your MyCoolHeader's template from:
<template>
<content></content>
</template>
to:
<template>
<img src="logo.png">
<div show.bind="user">${user.name}</div>
<div show.bind="!user">Sign-in</div>
</template>
then change your server-generated page to something like this:
<html>
<body>
<my-cool-header></my-cool-header>
<div>Cachabled content</div>
</body>
</html>
Hope that helps. If this doesn't solve the problem or is not an acceptable solution, let me know.
Edit
After reading your reply and thinking about this a bit more I'm leaning towards removing the <my-cool-header> element. It's not providing any behavior, it only acts as a data loader, it's template is provided by the server-side rendering process and it's expected to be rendered outside of the aurelia templating system, there's no real need to re-render it. Here's what this approach would look like, let me know if it seems like a better fit:
<html>
<body>
<div class="my-cool-header">
<img src="logo.png">
<div show.bind="user">${user.name}</div>
<div show.bind="!user">Sign-in</div>
</div>
<div>Cachabled content</div>
</body>
</html>
import {MainData} from './main-data';
import {UserService} from './user';
export function configure(aurelia) {
const mainData = aurelia.container.get(MainData);
const userService = aurelia.container.get(UserService);
aurelia.use
.standardConfiguration()
.developmentLogging();
Promise.all([
this.userService.get(),
aurelia.start()
]).then(([user, a]) => {
mainData.user = user;
a.enhance(mainData, document.body);
});
}
To supplement Jeremy's answer, if you did change the template to:
<template>
<img src="logo.png">
<div show.bind="user">${user.name}</div>
<div show.bind="!user">Sign-in</div>
</template>
This content would be present when Aurelia processed the element and in the absence of a content selector, anything inside the custom element tags will be replaced by the template
If you then put your non-javascript content inside the custom element tags:
<my-cool-header>
<div>This stuff will be visible when JS is turned off</div>
</my-cool-header>
In the example above, in the absence of JS the div should still be there as Aurelia won't remove it from the DOM.
(This is of course assuming your server side tech doesn't mangle/fix the unknown HTML tags in the DOM for some reason when serving pages - which it probably won't since it would break Aurelia anyway)
EDIT:
The alternative you may be looking for is the #processContent decorator.
This allows you to pass a callback function that runs before Aurelia inspects the element.
At this point you could just lift the content between the custom element tags and add it as a child of the template element. The content should then be in scope of your viewmodel.
This way you can have the same markup in between the custom element tags with no javascript, and inside your template in the correct scope when Aurelia is running
import {processContent, TargetInstruction, inject} from 'aurelia-framework';
#inject(Element, TargetInstruction)
#processContent(function(viewCompiler, viewResources, element, instruction) {
// Do stuff
instruction.templateContent = element;
return true;
})
class MyViewModel {
constructor(element, targetInstruction) {
var behavior = targetInstruction.behaviorInstructions[0];
var userTemplate = behavior.templateContent;
element.addChild(userTemplate);
}
}
Disclaimer: the above code hasn't been tested and I pulled it from my grid which is several releases old - you may need to tweak

Categories

Resources