I would like to product php code within HTML with heXa. For example:
<?php
$temp = 'Hello';
?>
<html>
<body>
<?php echo $temp?>
</body>
</html>
How would I write the above using haxe? The haxe site shows you how to produce PHP code, but it doesn't mention how to produce PHP with HTML.
Haxe isn't a scripting language that can be called from within a html file in that way. You have to adapt a workflow where you prepare your html templates and your data as separate units and let the compiled application combine them according to your wishes.
Here's a quick example that should work in any Haxe server target language (php, neko, cpp). (Maybe also java and c# - not sure if the Template implementation is ready) :
package ;
import haxe.Template;
import neko.Lib;
class Main
{
static function main()
{
var data = { greeting: 'Hello' };
var template = new Template('<html><body>::greeting::</body></html>');
var output = template.execute(data);
Sys.print(output);
}
}
There are a bunch of template engines for Haxe out there, for example the .NET Razor clone Erazor
Related
How do you import CSS into a ES6 module?
I receive the following error in browser console;
Failed to load module script: The server responded with a
non-JavaScript MIME type of "text/css". Strict MIME type checking is
enforced for module scripts per HTML spec.
Module below:
import { LitElement, html, css } from "lit-element";
import { MDCTextField } from "#material/textfield";
import style from "#material/textfield/dist/mdc.textfield.css";
export class MyWC extends LitElement {
static get styles() { return style; } //was using return css'...'
render() {
return html`
<label class="mdc-text-field mdc-text-field--textarea">
<textarea class="mdc-text-field__input" aria-labelledby="my-label-id" rows="8" cols="40" maxlength="140"></textarea>
...blah blah blah...
</label>
`;
}
#material/textfield & lit-element installed via npm OK. I'm using es-dev-server on linux.
ps - I want to use MDC web components but keep things as simple as possible.
Any help appreciated - Thanks.
The HTML spec currently only allows to import javascript modules. This is enforced by checking that the MIME type of the imported file is a javascript one, hence the error you're getting. The fact that in some environments (especially with bundlers/transpilers) importing other resource types is possible may give the wrong impression that it is case also in the browser.
To use this kind of import
import style from "#material/textfield/dist/mdc.textfield.css";
you would need some tool capable of transforming it into a CSSResult. A typical scenario is using bundlers like Rollup or Webpack with dedicated plugins/loaders (ie rollup-plugin-lit-css or lit-css-loader).
How would I compile
export default User
import socket from "./socket"
this ES6 javascript function with haxe?
import socket from "./socket"
let User = {
init(socket, element) {
if (!element) {
return
}
let userId = element.getAttribute("data-id")
userId= Math.random()
socket.connect()
this.onReady(userId, socket)
}
}
export default User
I actually had the same need a while ago, in order to integrate with Ember 2.0/Ember CLI. I didn't find a way with pure Haxe, the only alternative is to either:
1) Build a custom js generator - clunky because you lose the goodies of the built-in js generator since there's no granular control over what features you use - it's all or nothing - i.e you can't only change the output of a certain expression/type in the AST, and you can't reference the built-in generator and delegate to it when needed.
2) A pre-processor that parses the hx file, removes the ES6 code, compiles the file, and adds the ES6 code back, clunky as well, but might work.
3) Hack the OCAML code for the compiler and add some kind of class-level metadata tag, something like #:ESImport("import {foo} from bar"), #:ESExport("export default foo"). This could also be done with #1 (custom js gen), but by modifying the OCaml code, you get to keep the built-in js gen.
I've given up on integrating Haxe code with ES6 for now, I wish Haxe had better build-in support for ES6 (i.e an ES2016 generator) or more granular hooks for the JS Custom generator API.
As a reference, here's my message to the Haxe mailing list, about this very issue: https://groups.google.com/forum/#!topic/haxelang/jSTkkaNgfB8.
As of 4.0.0-rc.2, Haxe now supports generation of ES6 classes with the -D je-es=6 flag.
With that, this example...
class Main {
static function main() {
trace("Hello World");
}
}
...produces the following JavaScript code:
// Generated by Haxe 4.0.0-rc.2+43ed6c9b4
(function ($global) { "use strict";
class Main {
static main() {
console.log("source/Main.hx:3:","Hello World");
}
}
Main.main();
})({});
//# sourceMappingURL=run.js.map
Further ES6 support is planned:
ES6 types
ES6 module exports
Code Splitting
I'm writing a web app using TypeScript, Backbone, and Mustache. I want to use Requirejs for dependency loading.
I'm also using the Web Essentials visual studio plugin for TypeScript with the AMD compilation option turned on. For those that are not familiar with this, it will wrap your type script file in an AMD module if you import external modules.
For example:
In type script I import the following modules in type definition files.
export import Backbone = module("Backbone");
import mainTemplate = module("MainTemplate");
The output is something like:
define(["require", "exports", "Backbone", "MainTemplate"], function(require, exports, __Backbone__, __mainTemplate__) {
//...code goes here ...
});
For the template, I've declared the following in a type definition file:
declare module "MainTemplate" { }
In order to support requirejs plugins, you need to declare your module as:
declare module "text!MainTemplate.html" { }
I'd like to keep the module name free of plugins and file extensions. This would leave me with some flexibility in the future.
I have the following mapping in require.
require.config({
map: {
"MyModule": {
"MainTemplate": "text!MainTemplate.html"
}
}
}
This successfully invokes the text plugin however, the plugin loads the wrong url. Sifting through the source code for the text plugin, I found that the following code is the culprit.
load: function (name, req, onLoad, config) {
...
url = req.toUrl(nonStripName),
//returns "scripts/**text!**MainTemplate.html**.html**"
...
}
If I name the module, 'MainTemplate.html' it works fine but I'd like to keep the extension out of the module name.
I've modified the text plugin with a simple regex replacement to strip out the plugin reference and the duplicate extension.
Is there a better way to handle this?
Ran into similar issue. Solved finally. See TypeScript: compiling removes unreferenced imports
/// <amd-dependency path="text!templates/application.htm" />
var applicationTemplate = require('text!templates/application.htm');
For Typescript 1.0 this works for me.
First I created a .d.ts file which stores all module declarations for each text template.
//workaround for typescript's lack of support for requirejs text template notation
//remember that a reference to the import variable has to be found in the class, otherwise typescript ignores the import
declare module "text!views/details/details.html" {
var text: string;
export = text;
}
declare module "text!views/layout/layout.html" {
var text: string;
export = text;
}
declare module "text!views/home/home.html" {
var text: string;
export = text;
}
then to refer to the text template I add these lines on top of the class/module.
/// <reference path="../texttemplate.d.ts"/>
import detailsTemplate = require('text!views/details/details.html');
The reference line is not actually needed, since the .d.ts file is picked up globally. But I added it as a reminder of the workaround. It also makes it easy to ctrl+click to go the d.ts. file.
There is a slightly nicer way to do this (I'm using typescript 2.0)
Referenced here: https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html
This code expects that your requirejs configuration and plugins are set up correctly:
/// <amd-dependency path="text!./about.html" name="template"/>
declare let template: string;
This helped me a lot to migrate lagacy code to typescript.
Since TypeScript 0.9.0 I think you need to do the following:
/// <amd-dependency path="text!templates/application.htm" />
declare var require:(moduleId:string) => any;
var applicationTemplate:string = require("text!templates/application.htm");
Check out more at http://www.codebelt.com/typescript/typescript-amd-with-requirejs-tutorial/
We are using Backbone and require.js for our TypeScript applications.
We don't use the
import backbone = module("Backbone")
syntax, but rather use a
/// <reference path="../../modules/Backbone.d.ts" />
reference, and then a BootStrapper.
This way, the 'text!htmlfile.html' syntax works perfectly with require.js.
I've put together a blog on using require.js with TypeScript and AMD:
http://blorkfish.wordpress.com/2012/10/23/typescript-organizing-your-code-with-amd-modules-and-require-js/
is it possible to add arguments to the sctipt element
e.g.
<script
...
src="XX.js"
></script>
i want to add the argument hello="world" so this is added to the page:
<script
...
src="XX.js"
hallo="welt"
></script>
Reason: I have a js library (aloha-editor) which depends on a parameter for loading it's plugins (and the main functionallity is actuall in a plugin). However I only want to load the plugin when the user want's to edit and requirejs is the best choice since it is used at other parts in the application.
If you are wrapping the aloha script in a define function you could pass arguments like this (link):
//in main appfile
require.config({
'config': {
'aloha': {
src: "XX.js",
hallo: "welt"
}
}
});
//and in the aloha file
define(['module'], function (module) {
var src = module.config().src,
hallo = module.config().hallo;
... // the aloha code
});
There was also an alternative "simplified" syntax in the docs.
Edit: Maybe I misunderstood the question, if you where asking if it's possible to add html attributes to a script tag already on the page: <script src='' data-src='xx.js' data-hallo='welt'></script> is the new html5 syntax for adding custom attributes to tags, everything preceded by data- is correct syntax.
when I check the html page source, the HTML tags and text content are compressed without blank and line, but inline javascript.
Just discovered something that works for me in Jade v0.30.0:
Rename your .js file with a .uglify extension
In your Jade template, use:
include name-of-javascript-file.uglify
Why it works: Digging into the Jade source code, I discovered a file called filters.js. In there, you'll see a dependency on transformers. In lib/transformers.js (of the transformers module), you will see the various transform utilities, including uglify. Apparently, Jade will call on any of those transformers if you match the right file extension in your include declaration.
I'm not sure about it and haven't tested it yet, but you can probalby add a filter and utilize UglifyJS. For example
var uglyParser = require("uglify-js").parser;
var uglyUgly = require("uglify-js").uglify;
var uglify = function(str) {
var ast = uglyParser.parse(str);
ast = uglyUgly.ast_mangle(ast);
ast = uglyUgly.ast_squeeze(ast);
return uglyUgly.gen_code(ast);
}
To be honest, I'm not sure where to put that in jade so it's treated as a filter. For now you should be able to just stick it at https://github.com/visionmedia/jade/blob/master/lib/filters.js.
The usage in jade would then be:
script(type="text/javascript")
:uglify
<Your JavaScript Code>
Again I haven't tested it. But I think it should work. I'll test it later today.
According to the docs, you can use any JSTransformer as a jade filter. So, where you would normally do this to inline JS:
script.
(function doSomething () { … })();
you should do it like this:
script
:uglify-js
(function doSomething () { … })();