mad_dtl.erl 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. -module(mad_dtl).
  2. %%-copyright('Sina Samavati').
  3. -compile([export_all, nowarn_export_all]).
  4. compile(Dir,Config) ->
  5. case mad_utils:get_value(erlydtl_opts, Config, []) of
  6. [] -> false;
  7. X -> compile_erlydtl_files(validate_erlydtl_opts(Dir,X)) end.
  8. get_kv(K, Opts, Default) ->
  9. V = mad_utils:get_value(K, Opts, Default),
  10. KV = {K, V},
  11. {KV, Opts -- [KV]}.
  12. file_to_beam(Bin, Filename) -> filename:join(Bin, filename:basename(Filename) ++ ".beam").
  13. validate_erlydtl_opts(Cwd, Opts) ->
  14. DefaultDocRoot = filename:join("priv", "templates"),
  15. {DocRoot, Opts1} = get_kv(doc_root, Opts, DefaultDocRoot),
  16. {OutDir, Opts2} = get_kv(out_dir, Opts1, "ebin"),
  17. {CompilerOpts, Opts3} = get_kv(compiler_options, Opts2, []),
  18. {SourceExt, Opts4} = get_kv(source_ext, Opts3, ".dtl"),
  19. {ModuleExt, Opts5} = get_kv(module_ext, Opts4, ""),
  20. {_, DocRootDir} = DocRoot,
  21. DocRoot1 = {doc_root, filename:join(Cwd, DocRootDir)},
  22. {_, OutDir1} = OutDir,
  23. OutDir2 = {out_dir, filename:join(Cwd, OutDir1)},
  24. Auto_Escape = case application:get_env(mad, compile_dtl_escape, false) of
  25. true -> {auto_escape, true};
  26. _ -> {auto_escape, false}
  27. end,
  28. [DocRoot1, OutDir2, CompilerOpts, Auto_Escape, SourceExt, ModuleExt|Opts5].
  29. module_name(File, Ext, NewExt) ->
  30. list_to_atom(filename:basename(File, Ext) ++ NewExt).
  31. compile_erlydtl_files(Opts) ->
  32. {{_, DocRoot}, Opts1} = get_kv(doc_root, Opts, ""),
  33. {{_, SourceExt}, Opts2} = get_kv(source_ext, Opts1, ""),
  34. {{_, ModuleExt}, Opts3} = get_kv(module_ext, Opts2, ""),
  35. {{_, OutDir}, _} = get_kv(out_dir, Opts3, ""),
  36. Files = filelib:fold_files(DocRoot, SourceExt, true,
  37. fun(F, Acc) -> [F|Acc] end, []),
  38. Compile = fun(F) ->
  39. ModuleName = module_name(F, SourceExt, ModuleExt),
  40. BeamFile = file_to_beam(OutDir, atom_to_list(ModuleName)),
  41. Compiled = mad_compile:is_compiled(BeamFile, F),
  42. case Compiled of false ->
  43. mad:info("DTL Compiling ~s~n", [F -- mad_utils:cwd()]),
  44. Res = erlydtl:compile(F, ModuleName, Opts3),
  45. file:change_time(BeamFile, calendar:local_time()),
  46. case Res of {error,Error} -> mad:info("Error: ~p~n",[Error]);
  47. OK -> OK end;
  48. true -> ok end
  49. end,
  50. lists:any(fun({error,_}) -> true;
  51. ({error,_,_}) -> true;
  52. ({ok, _}) -> false;
  53. (ok) -> false
  54. end, [Compile(F) || F <- Files]).