sunng87 / handlebars-rust

Rust templating with Handlebars
MIT License
1.29k stars 139 forks source link

HowTo: Embed JS in HTML? #464

Closed Anonyfox closed 3 years ago

Anonyfox commented 3 years ago

I currently want to build a standalone HTML file that is self-contained, eg.:

<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>

should be replaced with

<script> ... contents of the JS file ...</script>

so, i downloaded the file, used it in my code with include_str! but had no luck so far embedding it within my html template without breaking the code. Something in this file seems broken when trying to embed it.

On another project, I successfully embedded bootstrap with a helper like this:

    reg.register_template_string(
        "bootstrap",
        &format!(
            "<style>{}</style><script>{}</script>",
            include_str!("bootstrap.min.css"),
            include_str!("bootstrap.min.js")
        ),
    )?;

and using it in my template like this:

{{> bootstrap}}

... but the same technique doesn't work with https://remarkjs.com/downloads/remark-latest.min.js . Any idea on how to accomplish the embedding?

sunng87 commented 3 years ago

Can you post the error you have with remark-latest.min.js?

Anonyfox commented 3 years ago
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Template error: invalid handlebars syntax.
    --> Template error in "remark":22:944
     |
  19 |     }, { name: "avrasm", create: function (e) { return { case_insensitive: !0, lexemes: "\\.?" + e.IDENT_RE, keywords: { keyword: "adc add adiw and andi asr bclr bld brbc brbs brcc brcs break breq brge brhc brhs brid brie brlo brlt brmi brne brpl brsh brtc brts brvc brvs bset bst call cbi cbr clc clh cli cln clr cls clt clv clz com cp cpc cpi cpse dec eicall eijmp elpm eor fmul fmuls fmulsu icall ijmp in inc jmp ld ldd ldi lds lpm lsl lsr mov movw mul muls mulsu neg nop or ori out pop push rcall ret reti rjmp rol ror sbc sbr sbrc sbrs sec seh sbi sbci sbic sbis sbiw sei sen ser ses set sev sez sleep spm st std sts sub subi swap tst wdr", built_in: "r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 x|0 xh xl y|0 yh yl z|0 zh zl ucsr1c udr1 ucsr1a ucsr1b ubrr1l ubrr1h ucsr0c ubrr0h tccr3c tccr3a tccr3b tcnt3h tcnt3l ocr3ah ocr3al ocr3bh ocr3bl ocr3ch ocr3cl icr3h icr3l etimsk etifr tccr1c ocr1ch ocr1cl twcr twdr twar twsr twbr osccal xmcra xmcrb eicra spmcsr spmcr portg ddrg ping portf ddrf sreg sph spl xdiv rampz eicrb eimsk gimsk gicr eifr gifr timsk tifr mcucr mcucsr tccr0 tcnt0 ocr0 assr tccr1a tccr1b tcnt1h tcnt1l ocr1ah ocr1al ocr1bh ocr1bl icr1h icr1l tccr2 tcnt2 ocr2 ocdr wdtcr sfior eearh eearl eedr eecr porta ddra pina portb ddrb pinb portc ddrc pinc portd ddrd pind spdr spsr spcr udr0 ucsr0a ucsr0b ubrr0l acsr admux adcsr adch adcl porte ddre pine pinf", meta: ".byte .cseg .db .def .device .dseg .dw .endmacro .equ .eseg .exit .include .list .listmac .macro .nolist .org .set" }, contains: [e.C_BLOCK_COMMENT_MODE, e.COMMENT(";", "$", { relevance: 0 }), e.C_NUMBER_MODE, e.BINARY_NUMBER_MODE, { className: "number", begin: "\\b(\\$[a-zA-Z0-9]+|0o[0-7]+)" }, e.QUOTE_STRING_MODE, { className: "string", begin: "'", end: "[^\\\\]'", illegal: "[^\\\\][^']" }, { className: "symbol", begin: "^[A-Za-z0-9_.$]+:" }, { className: "meta", begin: "#", end: "$" }, { className: "subst", begin: "@[0-9]+" }] } } }, { name: "awk", create: function (e) { var t = { className: "variable", variants: [{ begin: /\$[\w\d#@][\w\d_]*/ }, { begin: /\$\{(.*?)}/ }] }, a = "BEGIN END if else while do for in break continue delete next nextfile function func exit|10", r = { className: "string", contains: [e.BACKSLASH_ESCAPE], variants: [{ begin: /(u|b)?r?'''/, end: /'''/, relevance: 10 }, { begin: /(u|b)?r?"""/, end: /"""/, relevance: 10 }, { begin: /(u|r|ur)'/, end: /'/, relevance: 10 }, { begin: /(u|r|ur)"/, end: /"/, relevance: 10 }, { begin: /(b|br)'/, end: /'/ }, { begin: /(b|br)"/, end: /"/ }, e.APOS_STRING_MODE, e.QUOTE_STRING_MODE] }; return { keywords: { keyword: a }, contains: [t, r, e.REGEXP_MODE, e.HASH_COMMENT_MODE, e.NUMBER_MODE] } } }, { name: "axapta", create: function (e) { return { keywords: "false int abstract private char boolean static null if for true while long throw finally protected final return void enum else break new catch byte super case short default double public try this switch continue reverse firstfast firstonly forupdate nofetch sum avg minof maxof count order group by asc desc index hint like dispaly edit client server ttsbegin ttscommit str real date container anytype common div mod", contains: [e.C_LINE_COMMENT_MODE, e.C_BLOCK_COMMENT_MODE, e.APOS_STRING_MODE, e.QUOTE_STRING_MODE, e.C_NUMBER_MODE, { className: "meta", begin: "#", end: "$" }, { className: "class", beginKeywords: "class interface", end: "{", excludeEnd: !0, illegal: ":", contains: [{ beginKeywords: "extends implements" }, e.UNDERSCORE_TITLE_MODE] }] } } }, { name: "bash", create: function (e) { var t = { className: "variable", variants: [{ begin: /\$[\w\d#@][\w\d_]*/ }, { begin: /\$\{(.*?)}/ }] }, a = { className: "string", begin: /"/, end: /"/, contains: [e.BACKSLASH_ESCAPE, t, { className: "variable", begin: /\$\(/, end: /\)/, contains: [e.BACKSLASH_ESCAPE] }] }, r = { className: "string", begin: /'/, end: /'/ }; return { aliases: ["sh", "zsh"], lexemes: /-?[a-z\._]+/, keywords: { keyword: "if then else elif fi for while in do done case esac function", literal: "true false", built_in: "break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp", _: "-ne -eq -lt -gt -f -d -e -s -l -a" }, contains: [{ className: "meta", begin: /^#![^\n]+sh\s*$/, relevance: 10 }, { className: "function", begin: /\w[\w\d_]*\s*\(\s*\)\s*\{/, returnBegin: !0, contains: [e.inherit(e.TITLE_MODE, { begin: /\w[\w\d_]*/ })], relevance: 0 }, e.HASH_COMMENT_MODE, a, r, t] } } }, { name: "basic", create: function (e) { return { case_insensitive: !0, illegal: "^.", lexemes: "[a-zA-Z][a-zA-Z0-9_$%!#]*", keywords: { keyword: "ABS ASC AND ATN AUTO|0 BEEP BLOAD|10 BSAVE|10 CALL CALLS CDBL CHAIN CHDIR CHR$|10 CINT CIRCLE CLEAR CLOSE CLS COLOR COM COMMON CONT COS CSNG CSRLIN CVD CVI CVS DATA DATE$ DEFDBL DEFINT DEFSNG DEFSTR DEF|0 SEG USR DELETE DIM DRAW EDIT END ENVIRON ENVIRON$ EOF EQV ERASE ERDEV ERDEV$ ERL ERR ERROR EXP FIELD FILES FIX FOR|0 FRE GET GOSUB|10 GOTO HEX$ IF|0 THEN ELSE|0 INKEY$ INP INPUT INPUT# INPUT$ INSTR IMP INT IOCTL IOCTL$ KEY ON OFF LIST KILL LEFT$ LEN LET LINE LLIST LOAD LOC LOCATE LOF LOG LPRINT USING LSET MERGE MID$ MKDIR MKD$ MKI$ MKS$ MOD NAME NEW NEXT NOISE NOT OCT$ ON OR PEN PLAY STRIG OPEN OPTION BASE OUT PAINT PALETTE PCOPY PEEK PMAP POINT POKE POS PRINT PRINT] PSET PRESET PUT RANDOMIZE READ REM RENUM RESET|0 RESTORE RESUME RETURN|0 RIGHT$ RMDIR RND RSET RUN SAVE SCREEN SGN SHELL SIN SOUND SPACE$ SPC SQR STEP STICK STOP STR$ STRING$ SWAP SYSTEM TAB TAN TIME$ TIMER TROFF TRON TO USR VAL VARPTR VARPTR$ VIEW WAIT WHILE WEND WIDTH WINDOW WRITE XOR" }, contains: [e.QUOTE_STRING_MODE, e.COMMENT("REM", "$", { relevance: 10 }), e.COMMENT("'", "$", { relevance: 0 }), { className: "symbol", begin: "^[0-9]+ ", relevance: 10 }, { className: "number", begin: "\\b([0-9]+[0-9edED.]*[#!]?)", relevance: 0 }, { className: "number", begin: "(&[hH][0-9a-fA-F]{1,4})" }, { className: "number", begin: "(&[oO][0-7]{1,6})" }] } } }, { name: "bnf", create: function (e) { return { contains: [{ className: "attribute", begin: /</, end: />/ }, { begin: /::=/, starts: { end: /$/, contains: [{ begin: /</, end: />/ }, e.C_LINE_COMMENT_MODE, e.C_BLOCK_COMMENT_MODE, e.APOS_STRING_MODE, e.QUOTE_STRING_MODE] } }] } } }, { name: "brainfuck", create: function (e) { var t = { className: "literal", begin: "[\\+\\-]", relevance: 0 }; return { aliases: ["bf"], contains: [e.COMMENT("[^\\[\\]\\.,\\+\\-<> \r\n]", "[\\[\\]\\.,\\+\\-<> \r\n]", { returnEnd: !0, relevance: 0 }), { className: "title", begin: "[\\[\\]]", relevance: 0 }, { className: "string", begin: "[\\.,]", relevance: 0 }, { begin: /\+\+|\-\-/, returnBegin: !0, contains: [t] }, t] } } }, { name: "cal", create: function (e) { var t = "div mod in and or not xor asserterror begin case do downto else end exit for if of repeat then to until while with var", a = "false true", r = [e.C_LINE_COMMENT_MODE, e.COMMENT(/\{/, /\}/, { relevance: 0 }), e.COMMENT(/\(\*/, /\*\)/, { relevance: 10 })], s = { className: "string", begin: /'/, end: /'/, contains: [{ begin: /''/ }] }, n = { className: "string", begin: /(#\d+)+/ }, i = { className: "number", begin: "\\b\\d+(\\.\\d+)?(DT|D|T)", relevance: 0 }, l = { className: "string", begin: '"', end: '"' }, o = { className: "function", beginKeywords: "procedure", end: /[:;]/, keywords: "procedure|10", contains: [e.TITLE_MODE, { className: "params", begin: /\(/, end: /\)/, keywords: t, contains: [s, n] }].concat(r) }, c = { className: "class", begin: "OBJECT (Table|Form|Report|Dataport|Codeunit|XMLport|MenuSuite|Page|Query) (\\d+) ([^\\r\\n]+)", returnBegin: !0, contains: [e.TITLE_MODE, o] }; return { case_insensitive: !0, keywords: { keyword: t, literal: a }, illegal: /\/\*/, contains: [s, n, i, l, e.NUMBER_MODE, c, o] } } }, { name: "capnproto", create: function (e) { return { aliases: ["capnp"], keywords: { keyword: "struct enum interface union group import using const annotation extends in of on as with from fixed", built_in: "Void Bool Int8 Int16 Int32 Int64 UInt8 UInt16 UInt32 UInt64 Float32 Float64 Text Data AnyPointer AnyStruct Capability List", literal: "true false" }, contains: [e.QUOTE_STRING_MODE, e.NUMBER_MODE, e.HASH_COMMENT_MODE, { className: "meta", begin: /@0x[\w\d]{16};/, illegal: /\n/ }, { className: "symbol", begin: /@\d+\b/ }, { className: "class", beginKeywords: "struct enum", end: /\{/, illegal: /\n/, contains: [e.inherit(e.TITLE_MODE, { starts: { endsWithParent: !0, excludeEnd: !0 } })] }, { className: "class", beginKeywords: "interface", end: /\{/, illegal: /\n/, contains: [e.inherit(e.TITLE_MODE, { starts: { endsWithParent: !0, excludeEnd: !0 } })] }] } } }, { name: "ceylon", create: function (e) { var t = "assembly module package import alias class interface object given value assign void function new of extends satisfies abstracts in out return break continue throw assert dynamic if else switch case for while try catch finally then let this outer super is exists nonempty", a = "shared abstract formal default actual variable late native deprecatedfinal sealed annotation suppressWarnings small", r = "doc by license see throws tagged", s = { className: "subst", excludeBegin: !0, excludeEnd: !0, begin: /``/, end: /``/, keywords: t, relevance: 10 }, n = [{ className: "string", begin: '"""', end: '"""', relevance: 10 }, { className: "string", begin: '"', end: '"', contains: [s] }, { className: "string", begin: "'", end: "'" }, { className: "number", begin: "#[0-9a-fA-F_]+|\\$[01_]+|[0-9_]+(?:\\.[0-9_](?:[eE][+-]?\\d+)?)?[kMGTPmunpf]?", relevance: 0 }]; return s.contains = n, { keywords: { keyword: t + " " + a, meta: r }, illegal: "\\$[^01]|#[^0-9a-fA-F]", contains: [e.C_LINE_COMMENT_MODE, e.COMMENT("/\\*", "\\*/", { contains: ["self"] }), { className: "meta", begin: '@[a-z]\\w*(?:\\:"[^"]*")?' }].concat(n) } } }, { name: "clojure-repl", create: function (e) { return { contains: [{ className: "meta", begin: /^([\w.-]+|\s*#_)=>/, starts: { end: /$/, subLanguage: "clojure" } }] } } }, { name: "clojure", create: function (e) { var t = { "builtin-name": "def defonce cond apply if-not if-let if not not= = < > <= >= == + / * - rem quot neg? pos? delay? symbol? keyword? true? false? integer? empty? coll? list? set? ifn? fn? associative? sequential? sorted? counted? reversible? number? decimal? class? distinct? isa? float? rational? reduced? ratio? odd? even? char? seq? vector? string? map? nil? contains? zero? instance? not-every? not-any? libspec? -> ->> .. . inc compare do dotimes mapcat take remove take-while drop letfn drop-last take-last drop-while while intern condp case reduced cycle split-at split-with repeat replicate iterate range merge zipmap declare line-seq sort comparator sort-by dorun doall nthnext nthrest partition eval doseq await await-for let agent atom send send-off release-pending-sends add-watch mapv filterv remove-watch agent-error restart-agent set-error-handler error-handler set-error-mode! error-mode shutdown-agents quote var fn loop recur throw try monitor-enter monitor-exit defmacro defn defn- macroexpand macroexpand-1 for dosync and or when when-not when-let comp juxt partial sequence memoize constantly complement identity assert peek pop doto proxy defstruct first rest cons defprotocol cast coll deftype defrecord last butlast sigs reify second ffirst fnext nfirst nnext defmulti defmethod meta with-meta ns in-ns create-ns import refer keys select-keys vals key val rseq name namespace promise into transient persistent! conj! assoc! dissoc! pop! disj! use class type num float double short byte boolean bigint biginteger bigdec print-method print-dup throw-if printf format load compile get-in update-in pr pr-on newline flush read slurp read-line subvec with-open memfn time re-find re-groups rand-int rand mod locking assert-valid-fdecl alias resolve ref deref refset swap! reset! set-validator! compare-and-set! alter-meta! reset-meta! commute get-validator alter ref-set ref-history-count ref-min-history ref-max-history ensure sync io! new next conj set! to-array future future-call into-array aset gen-class reduce map filter find empty hash-map hash-set sorted-map sorted-map-by sorted-set sorted-set-by vec vector seq flatten reverse assoc dissoc list disj get union difference intersection extend extend-type extend-protocol int nth delay count concat chunk chunk-buffer chunk-append chunk-first chunk-rest max min dec unchecked-inc-int unchecked-inc unchecked-dec-inc unchecked-dec unchecked-negate unchecked-add-int unchecked-add unchecked-subtract-int unchecked-subtract chunk-next chunk-cons chunked-seq? prn vary-meta lazy-seq spread list* str find-keyword keyword symbol gensym force rationalize" }, a = "a-zA-Z_\\-!.?+*=<>&#'", r = "[" + a + "][" + a + "0-9/;:]*", s = "[-+]?\\d+(\\.\\d+)?", n = { begin: r, relevance: 0 }, i = { className: "number", begin: s, relevance: 0 }, l = e.inherit(e.QUOTE_STRING_MODE, { illegal: null }), o = e.COMMENT(";", "$", { relevance: 0 }), c = { className: "literal", begin: /\b(true|false|nil)\b/ }, d = { begin: "[\\[\\{]", end: "[\\]\\}]" }, m = { className: "comment", begin: "\\^" + r }, u = e.COMMENT("\\^\\{", "\\}"), h = { className: "symbol", begin: "[:]{1,2}" + r }, p = { begin: "\\(", end: "\\)" }, g = { endsWithParent: !0, relevance: 0 }, b = { keywords: t, lexemes: r, className: "name", begin: r, starts: g }, _ = [p, l, m, u, o, h, d, i, c, n]; return p.contains = [e.COMMENT("comment", ""), b, g], g.contains = _, d.contains = _, { aliases: ["clj"], illegal: /\S/, contains: [p, l, m, u, o, h, d, i, c] } } }, { name: "cmake", create: function (e) { return { aliases: ["cmake.in"], case_insensitive: !0, keywords: { keyword: "add_custom_command add_custom_target add_definitions add_dependencies add_executable add_library add_subdirectory add_test aux_source_directory break build_command cmake_minimum_required cmake_policy configure_file create_test_sourcelist define_property else elseif enable_language enable_testing endforeach endfunction endif endmacro endwhile execute_process export find_file find_library find_package find_path find_program fltk_wrap_ui foreach function get_cmake_property get_directory_property get_filename_component get_property get_source_file_property get_target_property get_test_property if include include_directories include_external_msproject include_regular_expression install link_directories load_cache load_command macro mark_as_advanced message option output_required_files project qt_wrap_cpp qt_wrap_ui remove_definitions return separate_arguments set set_directory_properties set_property set_source_files_properties set_target_properties set_tests_properties site_name source_group string target_link_libraries try_compile try_run unset variable_watch while build_name exec_program export_library_dependencies install_files install_programs install_targets link_libraries make_directory remove subdir_depends subdirs use_mangled_mesa utility_source variable_requires write_file qt5_use_modules qt5_use_package qt5_wrap_cpp on off true false and or equal less greater strless strgreater strequal matches" }, contains: [{ className: "variable", begin: "\\${", end: "}" }, e.HASH_COMMENT_MODE, e.QUOTE_STRING_MODE, e.NUMBER_MODE] } } }, { name: "coffeescript", create: function (e) { var t = { keyword: "in if for while finally new do return else break catch instanceof throw try this switch continue typeof delete debugger super then unless until loop of by when and or is isnt not", literal: "true false null undefined yes no on off", built_in: "npm require console print module global window document" }, a = "[A-Za-z$_][0-9A-Za-z$_]*", r = { className: "subst", begin: /#\{/, end: /}/, keywords: t }, s = [e.BINARY_NUMBER_MODE, e.inherit(e.C_NUMBER_MODE, { starts: { end: "(\\s*/)?", relevance: 0 } }), { className: "string", variants: [{ begin: /'''/, end: /'''/, contains: [e.BACKSLASH_ESCAPE] }, { begin: /'/, end: /'/, contains: [e.BACKSLASH_ESCAPE] }, { begin: /"""/, end: /"""/, contains: [e.BACKSLASH_ESCAPE, r] }, { begin: /"/, end: /"/, contains: [e.BACKSLASH_ESCAPE, r] }] }, { className: "regexp", variants: [{ begin: "///", end: "///", contains: [r, e.HASH_COMMENT_MODE] }, { begin: "//[gim]*", relevance: 0 }, { begin: /\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)/ }] }, { begin: "@" + a }, { begin: "`", end: "`", excludeBegin: !0, excludeEnd: !0, subLanguage: "javascript" }]; r.contains = s; var n = e.inherit(e.TITLE_MODE, { begin: a }), i = "(\\(.*\\))?\\s*\\B[-=]>", l = { className: "params", begin: "\\([^\\(]", returnBegin: !0, contains: [{ begin: /\(/, end: /\)/, keywords: t, contains: ["self"].concat(s) }] }; return { aliases: ["coffee", "cson", "iced"], keywords: t, illegal: /\/\*/, contains: s.concat([e.COMMENT("###", "###"), e.HASH_COMMENT_MODE, { className: "function", begin: "^\\s*" + a + "\\s*=\\s*" + i, end: "[-=]>", returnBegin: !0, contains: [n, l] }, { begin: /[:\(,=]\s*/, relevance: 0, contains: [{ className: "function", begin: i, end: "[-=]>", returnBegin: !0, contains: [l] }] }, { className: "class", beginKeywords: "class", end: "$", illegal: /[:="\[\]]/, contains: [{ beginKeywords: "extends", endsWithParent: !0, illegal: /[:="\[\]]/, contains: [n] }, n] }, { begin: a + ":", end: ":", returnBegin: !0, returnEnd: !0, relevance: 0 }]) } } }, { name: "coq", create: function (e) { return { keywords: { keyword: "_ as at cofix else end exists exists2 fix for forall fun if IF in let match mod Prop return Set then Type using where with Abort About Add Admit Admitted All Arguments Assumptions Axiom Back BackTo Backtrack Bind Blacklist Canonical Cd Check Class Classes Close Coercion Coercions CoFixpoint CoInductive Collection Combined Compute Conjecture Conjectures Constant constr Constraint Constructors Context Corollary CreateHintDb Cut Declare Defined Definition Delimit Dependencies DependentDerive Drop eauto End Equality Eval Example Existential Existentials Existing Export exporting Extern Extract Extraction Fact Field Fields File Fixpoint Focus for From Function Functional Generalizable Global Goal Grab Grammar Graph Guarded Heap Hint HintDb Hints Hypotheses Hypothesis ident Identity If Immediate Implicit Import Include Inductive Infix Info Initial Inline Inspect Instance Instances Intro Intros Inversion Inversion_clear Language Left Lemma Let Libraries Library Load LoadPath Local Locate Ltac ML Mode Module Modules Monomorphic Morphism Next NoInline Notation Obligation Obligations Opaque Open Optimize Options Parameter Parameters Parametric Path Paths pattern Polymorphic Preterm Print Printing Program Projections Proof Proposition Pwd Qed Quit Rec Record Recursive Redirect Relation Remark Remove Require Reserved Reset Resolve Restart Rewrite Right Ring Rings Save Scheme Scope Scopes Script Search SearchAbout SearchHead SearchPattern SearchRewrite Section Separate Set Setoid Show Solve Sorted Step Strategies Strategy Structure SubClass Table Tables Tactic Term Test Theorem Time Timeout Transparent Type Typeclasses Types Undelimit Undo Unfocus Unfocused Unfold Universe Universes Unset Unshelve using Variable Variables Variant Verbose Visibility where with", built_in: "abstract absurd admit after apply as assert assumption at auto autorewrite autounfold before bottom btauto by case case_eq cbn cbv change classical_left classical_right clear clearbody cofix compare compute congruence constr_eq constructor contradict contradiction cut cutrewrite cycle decide decompose dependent destruct destruction dintuition discriminate discrR do double dtauto eapply eassumption eauto ecase econstructor edestruct ediscriminate eelim eexact eexists einduction einjection eleft elim elimtype enough equality erewrite eright esimplify_eq esplit evar exact exactly_once exfalso exists f_equal fail field field_simplify field_simplify_eq first firstorder fix fold fourier functional generalize generalizing gfail give_up has_evar hnf idtac in induction injection instantiate intro intro_pattern intros intuition inversion inversion_clear is_evar is_var lapply lazy left lia lra move native_compute nia nsatz omega once pattern pose progress proof psatz quote record red refine reflexivity remember rename repeat replace revert revgoals rewrite rewrite_strat right ring ring_simplify rtauto set setoid_reflexivity setoid_replace setoid_rewrite setoid_symmetry setoid_transitivity shelve shelve_unifiable simpl simple simplify_eq solve specialize split split_Rabs split_Rmult stepl stepr subst sum swap symmetry tactic tauto time timeout top transitivity trivial try tryif unfold unify until using vm_compute with" }, contains: [e.QUOTE_STRING_MODE, e.COMMENT("\\(\\*", "\\*\\)"), e.C_NUMBER_MODE, { className: "type", excludeBegin: !0, begin: "\\|\\s*", end: "\\w+" }, { begin: /[-=]>/ }] } } }, { name: "cos", create: function (e) { var t = { className: "string", variants: [{ begin: '"', end: '"', contains: [{ begin: '""', relevance: 0 }] }] }, a = { className: "number", begin: "\\b(\\d+(\\.\\d*)?|\\.\\d+)", relevance: 0 }, r = "property parameter class classmethod clientmethod extends as break catch close continue do d|0 else elseif for goto halt hang h|0 if job j|0 kill k|0 lock l|0 merge new open quit q|0 read r|0 return set s|0 tcommit throw trollback try tstart use view while write w|0 xecute x|0 zkill znspace zn ztrap zwrite zw zzdump zzwrite print zbreak zinsert zload zprint zremove zsave zzprint mv mvcall mvcrt mvdim mvprint zquit zsync ascii"; return { case_insensitive: !0, aliases: ["cos", "cls"], keywords: r, contains: [a, t, e.C_LINE_COMMENT_MODE, e.C_BLOCK_COMMENT_MODE, { className: "comment", begin: /;/, end: "$", relevance: 0 }, { className: "built_in", begin: /(?:\$\$?|\.\.)\^?[a-zA-Z]+/ }, { className: "built_in", begin: /\$\$\$[a-zA-Z]+/ }, { className: "built_in", begin: /%[a-z]+(?:\.[a-z]+)*/ }, { className: "symbol", begin: /\^%?[a-zA-Z][\w]*/ }, { className: "keyword", begin: /##class|##super|#define|#dim/ }, { begin: /&sql\(/, end: /\)/, excludeBegin: !0, excludeEnd: !0, subLanguage: "sql" }, { begin: /&(js|jscript|javascript)</, end: />/, excludeBegin: !0, excludeEnd: !0, subLanguage: "javascript" }, { begin: /&html<\s*</, end: />\s*>/, subLanguage: "xml" }] } } }, { name: "1c", create: function (e) { var t = "[a-zA-Zа-яА-Я][a-zA-Z0-9_а-яА-Я]*", a = "возврат дата для если и или иначе иначеесли исключение конецесли конецпопытки конецпроцедуры конецфункции конеццикла константа не перейти перем перечисление по пока попытка прервать продолжить процедура строка тогда фс функция цикл число экспорт", r = "ansitooem oemtoansi ввестивидсубконто ввестидату ввестизначение ввестиперечисление ввестипериод ввестиплансчетов ввестистроку ввестичисло вопрос восстановитьзначение врег выбранныйплансчетов вызватьисключение датагод датамесяц датачисло добавитьмесяц завершитьработусистемы заголовоксистемы записьжурналарегистрации запуститьприложение зафиксироватьтранзакцию значениевстроку значениевстрокувнутр значениевфайл значениеизстроки значениеизстрокивнутр значениеизфайла имякомпьютера имяпользователя каталогвременныхфайлов каталогиб каталогпользователя каталогпрограммы кодсимв командасистемы конгода конецпериодаби конецрассчитанногопериодаби конецстандартногоинтервала конквартала конмесяца коннедели лев лог лог10 макс максимальноеколичествосубконто мин монопольныйрежим названиеинтерфейса названиенабораправ назначитьвид назначитьсчет найти найтипомеченныенаудаление найтиссылки началопериодаби началостандартногоинтервала начатьтранзакцию начгода начквартала начмесяца начнедели номерднягода номерднянедели номернеделигода нрег обработкаожидания окр описаниеошибки основнойжурналрасчетов основнойплансчетов основнойязык открытьформу открытьформумодально отменитьтранзакцию очиститьокносообщений периодстр полноеимяпользователя получитьвремята получитьдатута получитьдокументта получитьзначенияотбора получитьпозициюта получитьпустоезначение получитьта прав праводоступа предупреждение префиксавтонумерации пустаястрока пустоезначение рабочаядаттьпустоезначение рабочаядата разделительстраниц разделительстрок разм разобратьпозициюдокумента рассчитатьрегистрына рассчитатьрегистрыпо сигнал симв символтабуляции создатьобъект сокрл сокрлп сокрп сообщить состояние сохранитьзначение сред статусвозврата стрдлина стрзаменить стрколичествострок стрполучитьстроку  стрчисловхождений сформироватьпозициюдокумента счетпокоду текущаядата текущеевремя типзначения типзначениястр удалитьобъекты установитьтана установитьтапо фиксшаблон формат цел шаблон", s = { begin: '""' }, n = { className: "string", begin: '"', end: '"|$', contains: [s] }, i = { className: "string", begin: "\\|", end: '"|$', contains: [s] }; return { case_insensitive: !0, lexemes: t, keywords: { keyword: a, built_in: r }, contains: [e.C_LINE_COMMENT_MODE, e.NUMBER_MODE, n, i, { className: "function", begin: "(процедура|функция)", end: "$", lexemes: t, keywords: "процедура функция", contains: [{ begin: "экспорт", endsWithParent: !0, lexemes: t, keywords: "экспорт", contains: [e.C_LINE_COMMENT_MODE] }, { className: "params", begin: "\\(", end: "\\)", lexemes: t, keywords: "знач", contains: [n, i] }, e.C_LINE_COMMENT_MODE, e.inherit(e.TITLE_MODE, { begin: t })] }, { className: "meta", begin: "#", end: "$" }, { className: "number", begin: "'\\d{2}\\.\\d{2}\\.(\\d{2}|\\d{4})'" }] } } }, { name: "crmsh", create: function (e) { var t = "primitive rsc_template", a = "group clone ms master location colocation order fencing_topology rsc_ticket acl_target acl_group user role tag xml", r = "property rsc_defaults op_defaults", s = "params meta operations op rule attributes utilization", n = "read write deny defined not_defined in_range date spec in ref reference attribute type xpath version and or lt gt tag lte gte eq ne \\", i = "number string", l = "Master Started Slave Stopped start promote demote stop monitor true false"; return { aliases: ["crm", "pcmk"], case_insensitive: !0, keywords: { keyword: s + " " + n + " " + i, literal: l }, contains: [e.HASH_COMMENT_MODE, { beginKeywords: "node", starts: { end: "\\s*([\\w_-]+:)?", starts: { className: "title", end: "\\s*[\\$\\w_][\\w_-]*" } } }, { beginKeywords: t, starts: { className: "title", end: "\\s*[\\$\\w_][\\w_-]*", starts: { end: "\\s*@?[\\w_][\\w_\\.:-]*" } } }, { begin: "\\b(" + a.split(" ").join("|") + ")\\s+", keywords: a, starts: { className: "title", end: "[\\$\\w_][\\w_-]*" } }, { beginKeywords: r, starts: { className: "title", end: "\\s*([\\w_-]+:)?" } }, e.QUOTE_STRING_MODE, { className: "meta", begin: "(ocf|systemd|service|lsb):[\\w_:-]+", relevance: 0 }, { className: "number", begin: "\\b\\d+(\\.\\d+)?(ms|s|h|m)?", relevance: 0 }, { className: "literal", begin: "[-]?(infinity|inf)", relevance: 0 }, { className: "attr", begin: /([A-Za-z\$_\#][\w_-]+)=/, relevance: 0 }, { className: "tag", begin: "</?", end: "/?>", relevance: 0 }] } } }, { name: "crystal", create: function (e) { function t(e, t) { var a = [{ begin: e, end: t }]; return a[0].contains = a, a } var a = "(_[uif](8|16|32|64))?", r = "[a-zA-Z_]\\w*[!?=]?", s = "!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~", n = "[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\][=?]?", i = { keyword: "abstract alias as asm begin break case class def do else elsif end ensure enum extend for fun if ifdef include instance_sizeof is_a? lib macro module next of out pointerof private protected rescue responds_to? return require self sizeof struct super then type typeof union unless until when while with yield __DIR__ __FILE__ __LINE__", literal: "false nil true" }, l = { className: "subst", begin: "#{", end: "}", keywords: i }, o = { className: "template-variable", variants: [{ begin: "\\{\\{", end: "\\}\\}" }, { begin: "\\{%", end: "%\\}" }], keywords: i }, c = { className: "string", contains: [e.BACKSLASH_ESCAPE, l], variants: [{ begin: /'/, end: /'/ }, { begin: /"/, end: /"/ }, { begin: /`/, end: /`/ }, { begin: "%w?\\(", end: "\\)", contains: t("\\(", "\\)") }, { begin: "%w?\\[", end: "\\]", contains: t("\\[", "\\]") }, { begin: "%w?{", end: "}", contains: t("{", "}") }, { begin: "%w?<", end: ">", contains: t("<", ">") }, { begin: "%w?/", end: "/" }, { begin: "%w?%", end: "%" }, { begin: "%w?-", end: "-" }, { begin: "%w?\\|", end: "\\|" }], relevance: 0 }, d = { begin: "(" + s + ")\\s*", contains: [{ className: "regexp", contains: [e.BACKSLASH_ESCAPE, l], variants: [{ begin: "//[a-z]*", relevance: 0 }, { begin: "/", end: "/[a-z]*" }, { begin: "%r\\(", end: "\\)", contains: t("\\(", "\\)") }, { begin: "%r\\[", end: "\\]", contains: t("\\[", "\\]") }, { begin: "%r{", end: "}", contains: t("{", "}") }, { begin: "%r<", end: ">", contains: t("<", ">") }, { begin: "%r/", end: "/" }, { begin: "%r%", end: "%" }, { begin: "%r-", end: "-" }, { begin: "%r\\|", end: "\\|" }] }], relevance: 0 }, m = { className: "regexp", contains: [e.BACKSLASH_ESCAPE, l], variants: [{ begin: "%r\\(", end: "\\)", contains: t("\\(", "\\)") }, { begin: "%r\\[", end: "\\]", contains: t("\\[", "\\]") }, { begin: "%r{", end: "}", contains: t("{", "}") }, { begin: "%r<", end: ">", contains: t("<", ">") }, { begin: "%r/", end: "/" }, { begin: "%r%", end: "%" }, { begin: "%r-", end: "-" }, { begin: "%r\\|", end: "\\|" }], relevance: 0 }, u = { className: "meta", begin: "@\\[", end: "\\]", contains: [e.inherit(e.QUOTE_STRING_MODE, { className: "meta-string" })] }, h = [o, c, d, m, u, e.HASH_COMMENT_MODE, { className: "class", beginKeywords: "class module struct", end: "$|;", illegal: /=/, contains: [e.HASH_COMMENT_MODE, e.inherit(e.TITLE_MODE, { begin: "[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?" }), { begin: "<" }] }, { className: "class", beginKeywords: "lib enum union", end: "$|;", illegal: /=/, contains: [e.HASH_COMMENT_MODE, e.inherit(e.TITLE_MODE, { begin: "[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?" })], relevance: 10 }, { className: "function", beginKeywords: "def", end: /\B\b/, contains: [e.inherit(e.TITLE_MODE, { begin: n, endsParent: !0 })] }, { className: "function", beginKeywords: "fun macro", end: /\B\b/, contains: [e.inherit(e.TITLE_MODE, { begin: n, endsParent: !0 })], relevance: 5 }, { className: "symbol", begin: e.UNDERSCORE_IDENT_RE + "(\\!|\\?)?:", relevance: 0 }, { className: "symbol", begin: ":", contains: [c, { begin: n }], relevance: 0 }, { className: "number", variants: [{ begin: "\\b0b([01_]*[01])" + a }, { begin: "\\b0o([0-7_]*[0-7])" + a }, { begin: "\\b0x([A-Fa-f0-9_]*[A-Fa-f0-9])" + a }, { begin: "\\b(([0-9][0-9_]*[0-9]|[0-9])(\\.[0-9_]*[0-9])?([eE][+-]?[0-9_]*[0-9])?)" + a }], relevance: 0 }]; return l.contains = h, o.contains = h.slice(1), { aliases: ["cr"], lexemes: r, keywords: i, contains: h } } }, {
  20 |       name: "cs", create: function (e) {
  21 |         var t = { keyword: "abstract as base bool break byte case catch char checked const continue decimal dynamic default delegate do double else enum event explicit extern finally fixed float for foreach goto if implicit in int interface internal is lock long when object operator out override params private protected public readonly ref sbyte sealed short sizeof stackalloc static string struct switch this try typeof uint ulong unchecked unsafe ushort using virtual volatile void while async nameof ascending descending from get group into join let orderby partial select set value var where yield", literal: "null false true" }, a = { className: "string", begin: '@"', end: '"', contains: [{ begin: '""' }] }, r = e.inherit(a, { illegal: /\n/ }), s = { className: "subst", begin: "{", end: "}", keywords: t }, n = e.inherit(s, { illegal: /\n/ }), i = { className: "string", begin: /\$"/, end: '"', illegal: /\n/, contains: [{ begin: "{{" }, { begin: "}}" }, e.BACKSLASH_ESCAPE, n] }, l = { className: "string", begin: /\$@"/, end: '"', contains: [{ begin: "{{" }, { begin: "}}" }, { begin: '""' }, s] }, o = e.inherit(l, { illegal: /\n/, contains: [{ begin: "{{" }, { begin: "}}" }, { begin: '""' }, n] }); s.contains = [l, i, a, e.APOS_STRING_MODE, e.QUOTE_STRING_MODE, e.C_NUMBER_MODE, e.C_BLOCK_COMMENT_MODE], n.contains = [o, i, r, e.APOS_STRING_MODE, e.QUOTE_STRING_MODE, e.C_NUMBER_MODE, e.inherit(e.C_BLOCK_COMMENT_MODE, { illegal: /\n/ })]; var c = { variants: [l, i, a, e.APOS_STRING_MODE, e.QUOTE_STRING_MODE] }, d = e.IDENT_RE + "(<" + e.IDENT_RE + ">)?(\\[\\])?"; return {
     |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------^----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  22 |           aliases: ["csharp"], keywords: t, illegal: /::/, contains: [e.COMMENT("///", "$", { returnBegin: !0, contains: [{ className: "doctag", variants: [{ begin: "///", relevance: 0 }, { begin: "<!--|-->" }, { begin: "</?", end: ">" }] }] }), e.C_LINE_COMMENT_MODE, e.C_BLOCK_COMMENT_MODE, { className: "meta", begin: "#", end: "$", keywords: { "meta-keyword": "if else elif endif define undef warning error line region endregion pragma checksum" } }, c, e.C_NUMBER_MODE, {
  23 |             beginKeywords: "class interface", end: /[{;=]/, illegal: /[^\s:]/, contains: [e.TITLE_MODE, e.C_LINE_COMMENT_MODE, e.C_BLOCK_COMMENT_MODE]
  24 |           }, { beginKeywords: "namespace", end: /[{;=]/, illegal: /[^\s:]/, contains: [e.inherit(e.TITLE_MODE, { begin: "[a-zA-Z](\\.?\\w)*" }), e.C_LINE_COMMENT_MODE, e.C_BLOCK_COMMENT_MODE] }, { beginKeywords: "new return throw await", relevance: 0 }, { className: "function", begin: "(" + d + "\\s+)+" + e.IDENT_RE + "\\s*\\(", returnBegin: !0, end: /[{;=]/, excludeEnd: !0, keywords: t, contains: [{ begin: e.IDENT_RE + "\\s*\\(", returnBegin: !0, contains: [e.TITLE_MODE], relevance: 0 }, { className: "params", begin: /\(/, end: /\)/, excludeBegin: !0, excludeEnd: !0, keywords: t, relevance: 0, contains: [c, e.C_NUMBER_MODE, e.C_BLOCK_COMMENT_MODE] }, e.C_LINE_COMMENT_MODE, e.C_BLOCK_COMMENT_MODE] }]
  25 |         }
     |
     = reason: invalid handlebars syntax.
sunng87 commented 3 years ago

That was because the javascript source may contains characters that handlebars treated as statements. You can inject these javascript files when rendering data. A helper can be handy for this:

template:

<script>{{resource "bootstrap.min.js"}}</script>
<style>{{resource "bootstrap.min.css"}}</script>

helper:

// const map
let resources = btreemap!{"bootstrap.min.js" => include_str!("bootstrap.min.js") ... };
r.register_helper(
            "resource",
            Box::new(
                |h: &Helper<'_, '_>,
                 _: &Registry<'_>,
                 _: &Context,
                 _: &mut RenderContext<'_, '_>,
                 out: &mut dyn Output|
                 -> Result<(), RenderError> {
                    let name = h.param(0).unwrap();
                    let content = resources.get(name).unwrap();
                    out.write(content.as_ref())
                },
            ),
        );
Anonyfox commented 3 years ago

alright, thank you, this works in principle. Indeed it looks like there is something wrong with the specific remark.js file, maybe some delimiter.

Screenshot

anyways, this is out of the scope of this crate I'd guess, so thanks for your support (and making my other embeddings (like bootstrap) better!).