how to precompile a dust template - dust.js

dust-compiler -s controllers/inbox/views/inbox.dust -d public/js/custom/inbox/messages.js
but i am getting error
if (err) throw err;
^
Error: ENOTDIR, scandir 'C:\jbk\buy2gthr-master\controllers\inbox\views\inbox.dust'
at Error (native)
i have inbox.dust file:
{>"../../../layout/layout"/}
{<css-content}
{/css-content}
{<page-content}
{/<page-content}
<script id="entry-template" type="text/x-tmpl">
{title}
<ul>
{#data}
<li>{name}</li>{~n}
{/data}
</ul>
</script>
**<div id="output"></div>**
{/page-content}
{<script-content}
<script src='/js/custom/inbox/inbox.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/dustjs-linkedin/2.7.2/dust-full.js'></script>
{/script-content}
and inbox.js file
$(document).ready(function () {
var data = {
"title": "Famous People",
"names" : [{ "name": "Larry" },{ "name": "Curly" },{ "name": "Moe" }]
}
var source = $("#entry-template").html();
var compiled = dust.compile(source, "intro");
console.log(compiled);
dust.loadSource(compiled);
dust.render("intro", data, function(err, out) {
if(err) console.log(err);
else
console.log(out);
$("#output").html(out);
});
});
still i am gettting
<div id="output"><ul></ul></div>

I'm not sure what dust compiler you're using, but just use dustc -- it comes with Dust.
You can read about all the dustc API options, but to precompile a single file you'd do something like
dustc controllers/inbox/views/inbox.dust --output=public/js/custom/inbox/messages.js
dustc compiles templates using absolute names instead of relative ones, because Dust is not filesystem-aware. Unless you've specifically set up your dust.onLoad function to handle relative paths, you'll want to make your includes look something like {> "inbox/messages" /}.

Related

Module parse failed: Unexpected character '�' (1:0) You may need an appropriate loader to handle this file type when added jpeg or mp3

I am working on a rails app with vue on front end. I am getting this error when try to add any image or mp3 file to my project. Please help me resolve this issue. Below is my environment.js file.
I am using webpack version
#rails/webpacker": "^3.2.0"
Below is the home.vue file which is causing the issue. When I try to add this mp3 file I get that error.
home.vue
<template>
<div>
<v-layout row wrap>
<v-flex xs12 sm4 md4 class="hidden-xs-only">
<p>
<!-- <a :href="require('images/company-overview.mp3')" target="_blank" title="Read Article">
<img src="../../images/company-logo.png"/>
</a> -->
</p>
</v-flex>
</v-layout>
</div>
</div>
</template>
<script>
export default {
};
</script>
environment.js
const { environment } = require('#rails/webpacker')
const coffee = require('./loaders/coffee');
const vue = require('./loaders/vue')
environment.loaders.append('coffee', coffee);
environment.loaders.append('vue', vue)
environment.loaders.append('jshint', {
test: /\.js$/, // include .js files
enforce: "pre", // preload the jshint loader
exclude: /node_modules/, // exclude any and all files in the node_modules folder
use: [{
loader: "jshint-loader"
}]
});
environment.loaders.append('signature_pad', {
test: /\.js?$/,
include: [/node_modules\/signature_pad/],
use: [{
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: [['env', { 'modules': false, 'targets': { 'node': 4 } }]]
}
}],
});
environment.loaders.append('sass', {
test: /\.(sass|scss)$/,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
{
loader: 'sass-loader',
options: {
// Prefer `dart-sass`
implementation: require('sass'),
},
},
],
});
const resolver = {
resolve: {
alias: {
'vue$': 'vue/dist/vue.js'
}
}
};
environment.config.merge(resolver);
module.exports = environment;

How to use es6 classes in *.cshtml

Added config files to the project (packege.json &webpack.config.json), added babel. At the moment it turns out like this: There is a directory / Scripts / build &Scripts / es6 (/main.js). When the npm run build command is run, everything builds ok (from themain.js file as indicated in the entry section of thewebpack.config.json file), the bundle.js file is created in the/ Scripts / build directory. In the above, there are no problems and everything is as it should. Now I want to use the js classes (their methods and properties) in the views (* .cshtml). How do i do this? Or need a different approach? If I write js code inmain.js, then I build it, then the code fulfills. But how do I make a function and run it (for example, by clicking a button)?
packege.json:
{
"name": "SensorDashboard",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack --progress --mode='development' -p"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.2",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"webpack": "^4.41.0",
"webpack-cli": "^3.3.9"
}
}
webpack.config.js
const path = require('path');
module.exports = {
entry: ['./Scripts/es6/main.js'],
output: {
path: path.resolve(__dirname, './Scripts/build'),
filename: 'bundle.js'
},
// IMPORTANT NOTE: If you are using Webpack 2 or above, replace "loaders" with "rules"
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}]
}
}
main.js:
import { Map, MyClass } from './Map';
(function () {
window.test_func = function () {
let cl = new MyClass();
cl.send("asd qweqwe");
};
})();
MyClass:
export class MyClass {
send(message) {
console.log(message);
}
}
then i runing command: npm run build, and a file was created (/Script/build/bundle.js)
then i try to use in *.cshtml:
#{Layout = null;}
...
<script src="~/Scripts/build/bundle.js"></script>
...
<div>....</div>
<script type="text/javascript">
$(document).ready(function () {
test_func(); //this work
let m = new MyClass(); //this don`t work (MyClass is not defined)
m.send("asd");
});
</script>
I think should be as simple as loading the script in your .cshtml file with your standard script tag at the bottom of the file which would look something like this:
#section Scripts {
<script src="#Url.Content("~/Scripts/build/main.js")"></script>
}
(possibly without the #Url.Content though I'm not 100% sure offhand)
You could then call a function by doing something like the following example, there are a few ways and probably depends on what your class looks like in your main.js:
#section Scripts {
<script src="#Url.Content("~/Scripts/build/main.js")"></script>
document.getElementById("myButton").onclick = function(){
let someClass = new Class();
someClass.DoSomething();
}
}
Let me know if I've misunderstood the question.
Edit:
Okay, sorry I did misunderstand.
Have a look at this link and see if it helps you? It looks like exactly what you need.
It has instructions on how to configure webpack to allow calling externally.
Looks as simple as adding these two lines to your output:
libraryTarget: 'var',
library: 'EntryPoint'
Where EntryPoint is the Name you want for the module .
So:
output: {
path: path.resolve(__dirname, 'dist/js'),
filename: 'app.bundle.js',
libraryTarget: 'var',
library: 'MyModule'
},
And that should allow you to just call
EntryPoint.send("asd qweqwe");

How can I include custom variables in AMP analytics?

A few months ago we introduced AMP to our Rails application. Our implementation includes the following:
<amp-analytics type="googleanalytics">
<script type="application/json">
{
"vars": {
"account": <%= ga.profile_code.inspect.html_safe %>
},
"triggers": {
"trackPageview": {
"on": "visible",
"request": "pageview"
}
}
}
</script>
</amp-analytics>
However, we now realise that we are missing some important custom variables that are used in the Google Analytics script for our non-AMP pages. These are set within a script as follows (where _gaq is an array):
<% ga.variables.each do |vars| %>
_gaq.push([ '_setCustomVar', <%= vars[:placement] %>, '<%= vars[:label] %>', '<%= vars[:variable] %>', <%= vars[:scope_number] %> ]);
<% end %>
Is it possible in AMP Analytics to set custom variables without any restriction on the variable names? If so, how?
You should notice that Custom Variables are only available for legacy google analytics tracking. For the latest implementation, you will need to replace your custom variables with custom dimensions instead. You could check the migration guide Here and Here.
After you have made a migration, you can check the implementation of sending custom dimensions and custom metrics in AMP page.
For example, you can send a custom dimension with a pageview by
including the Custom Dimension parameter (or any other parameters you
want to include with the hit) in the extraUrlParams section. This
section can be included at the trigger level for single requests or at
a global level to send the data with all requests.
<amp-analytics type="googleanalytics">
<script type="application/json">
{
"vars": {
"account": "UA-XXXXX-Y"
},
"extraUrlParams": {
"cd3": "AMP"
},
"triggers": {
"trackPageviewWithCustomData": {
"on": "visible",
"request": "pageview"
},
"trackEvent" : {
"on": "visible",
"request": "event",
"vars": {
"eventCategory": "ui-components",
"eventAction": "header-click"
},
"extraUrlParams": {
"ni": "1"
}
}
}
}
</script>
</amp-analytics>

Not able to load boot.js when rendered through AspNet-Core-MVC views

Not able to load boot.js when rendered through AspNet-Core-MVC views
I tried creating a ApsNet core + Angular2 RC4 application. Following are the steps which I have done to build the app
1. Created/updated the Package.json, systemjs.config.js, typings.json and tsconfig.json from the angular (RC4) quickstart tutorials with small changes to it as per my need
2. Placed all the angular2 components under scripts folder and also placed tsconfig.json under the same. But specified the outDir property to move all the transpiled .js files to wwwroot/appScripts/ folder.
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "commonjs",
"noEmitOnError": true,
"noImplicitAny": true,
"outDir": "../wwwroot/appScripts/",
"removeComments": false,
"sourceMap": true,
"suppressImplicitAnyIndexErrors": true,
"moduleResolution": "node",
"target": "es6"
},
"compileOnSave": true,
"exclude": [
"node_modules",
"wwwroot"
]
}
modified the systemjs.config.js as below to load the boot.js file for 'app' mapping
(function (global) {
// map tells the System loader where to look for things
var map = {
'app': 'app', // 'dist',
'#angular': 'lib/#angular',
'rxjs': 'lib/rxjs'
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'app': { main: 'boot.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' }
};
var ngPackageNames = [
'common',
'compiler',
'core',
'http',
'platform-browser',
'platform-browser-dynamic',
'router',
'router-deprecated',
'upgrade',
];
// Add package entries for angular packages
ngPackageNames.forEach(function (pkgName) {
packages['#angular/' + pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' };
}) ;
var config = {
map: map,
packages: packages
}
System.config(config);
})(this);
When the application loads, initally it lands on the login page and on authentication it redirects to the "Views/Home/index.cshtml" view which is rendered by the Login controller.
This "Views/Home/index.cshtml" view is having/under the layout set to "./shared/layout.cshtml" file
My "Views/Home/index.cshtml" is as below
#{
ViewData["Title"] = "Home Page";
Layout = "_Layout";
}
<!-- IE required polyfills, in this exact order -->
<script src="~/lib/core-js/client/shim.min.js"></script>
<script src="~/lib/zone.js/dist/zone.js"></script>
<script src="~/lib/reflect-metadata/Reflect.js"></script>
<script src="~/lib/systemjs/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
System.import('app').catch(function (err) { console.error(err); });
</script>
Earlier when i developed it from the scratch it was with the angular2 - beta 17 version, but now I have migrated to Angular2 RC4.
The problem now I am facing is the application is not able to load the boot.js file and I am getting the following error in the browser console
menu.js:103 Uncaught TypeError: $(...).tooltip is not a function
http://localhost:55413/Home/app/boot.js Failed to load resource: the server responded with a status of 404 (Not Found)
Index:54 Error: Error: XHR error (404 Not Found) loading http://localhost:55413/Home/app/boot.js
at XMLHttpRequest.wrapFn [as _onreadystatechange] (http://localhost:55413/lib/zone.js/dist/zone.js:769:30)
at ZoneDelegate.invokeTask (http://localhost:55413/lib/zone.js/dist/zone.js:356:38)
at Zone.runTask (http://localhost:55413/lib/zone.js/dist/zone.js:256:48)
at XMLHttpRequest.ZoneTask.invoke (http://localhost:55413/lib/zone.js/dist/zone.js:423:34)
Error loading http://localhost:55413/Home/app/boot.js(anonymous function) # Index:54
http://localhost:55413/app/boot.js Failed to load resource: the server responded with a status of 404 (Not Found)
Index:84 Error: Error: XHR error (404 Not Found) loading http://localhost:55413/app/boot.js
at XMLHttpRequest.wrapFn [as _onreadystatechange] (http://localhost:55413/lib/zone.js/dist/zone.js:769:30)
at ZoneDelegate.invokeTask (http://localhost:55413/lib/zone.js/dist/zone.js:356:38)
at Zone.runTask (http://localhost:55413/lib/zone.js/dist/zone.js:256:48)
at XMLHttpRequest.ZoneTask.invoke (http://localhost:55413/lib/zone.js/dist/zone.js:423:34)
Error loading http://localhost:55413/app/boot.js
Why the application is not able to identify/load the boot.js file, I am pointing to wrong path to load it? what is the change I need to do?
You are outputting your scripts to "appScripts/ or "scripts/" (your screenshots show two different "script" directories) but then you are trying to load your boot.js from the /Home/app directory. Change your system.config.ts:
var packages = {
'app': { main: 'scripts/boot.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' }
};
Or change your tsconfig outDir property.

Work with the simple-prefs module and export the values to a script stored in the data folder

I'm currently trying to add some preferences to a Firefox add-on. To do so, I'm playing with the new "simple-prefs" module. (Simple-Prefs on the Mozilla Blog)
The documentation is not very detailed and I face some problems understanding how I can retrieve the value attached to an option and export it to a JS script present in my data folder.
Let's say that I have only one optional setting in my addon, a boolean one, then my packages.json will look like this:
{
"name": "test",
...
"preferences": [{
"type": "bool",
"name": "option1",
"value": true,
"title": "Desc Option 1"
}]
}
Here is my main.js file [UPDATED]:
var pageMod = require("page-mod");
const data = require("self").data;
const prefSet = require("simple-prefs"); //Simple-prefs module
var option1 = prefSet.prefs.option1; //get the value for option1
function onPrefChange(prefName) { //Listen for changes
var prefName = prefSet.prefs[prefName];
}
prefSet.on("option1", onPrefChange);
exports.main = function() {
pageMod.PageMod({
include: ["https://mail.google.com/*","http://mail.google.com/*"],
contentScriptWhen: 'ready',
contentScriptFile: [data.url("jquery.js"),data.url("script.js")],
onAttach: function(worker)
{
worker.postMessage( option1 );
}
});
}
How can I retrieve the value attached to "option1" and export it in order to call it in my "script.js" file?
As usually, content scripts don't have access to the API - they can only receive messages from your extension's scripts. Here you would do:
pageMod.PageMod({
include: ["https://mail.google.com/*","http://mail.google.com/*"],
contentScriptWhen: 'ready',
contentScriptFile: [data.url("jquery.js"),data.url("script.js")],
onAttach: function(worker)
{
worker.postMessage(backtop);
}
});
And in the content script you would have the following code:
self.on("message", function(data)
{
alert("Received option value: " + data);
});
This message arrives asynchronously meaning that your content script won't know the option value initially - but that's how content scripts work.

Resources