Android freemarker template engine application

Android freemarker template engine application

What is freemarker?

Before we talk about this, we all know that the battle between web and native controls is just that. Performance, loading speed, traffic, data interaction…

If I use webView to load a url page, I have to parse the css through the network, parse the html code, and then render the generated page

What is freemarker? To put it simply, put the above HTML file into the application in advance, and just pass in the data when using it.

Freemarker advantages and applications

Save traffic and speed up web page loading

For example, some chart functions are more convenient to implement with js library, just put in html template in advance and pass in data. This greatly saves traffic and loading speed

Or if you already have a web page, you don't need to create an Android interface.

This feature is universal on iOS, so you only need one template to use it on both iOS and Android, which greatly saves development time.

Implementation principle

WebView loads local template engine process

main.tpl ——–> main.ftl+data ————> main.html ————> webView.load(main.html)

1. Import the freemarker library

  1. compile 'org.freemarker:freemarker-gae:2.3.25-incubating'  

2. Put the main.tpl file into the assets directory

  1. <! --main.tpl file-->  
  2. <html>
  3. <head>
  4. <title>Welcome!</title>
  5. </head>
  6. <body>
  7. <h1>Welcome ${ user }!</h1>
  8. <p>Our latest product:
  9. </body>
  10. </html>

3. Convert main.tpl to main.ftl

  1. private void prepareTemplate() throws IOException {
  2. //Get the app directory data/data/package/file/
  3. String destPath = getFilesDir().getAbsolutePath();
  4. File dir = new File(destPath);
  5. // Check if the folder exists and create it
  6. if (!dir.exists()) {
  7. dir.mkdir();
  8. }
  9. //The .ftl template file name and path to be generated
  10. String tempFile = destPath + "/" + "main.ftl" ;
  11. if (!(new File(tempFile).exists())) {
  12. //Get the .tpl template file in assets
  13. InputStream is = getResources().getAssets(). open ( "main.tpl" );
  14. //Generate .ftl template file
  15. FileOutputStream fos = new FileOutputStream(tempFile);
  16. byte[] buffer = new byte[7168];
  17. int   count = 0;
  18. while (( count = is . read (buffer)) > 0) {
  19. fos.write(buffer, 0, count );
  20. }
  21. fos.flush();
  22. fos.close ();
  23. is . close ();
  24. }
  25. }

4. Generate main.html file from main.ftl and data

  1. private void genHTML(Product object) {
  2. String destPath = getFilesDir().getAbsolutePath();
  3. FileWriter out = null ;
  4. //Data source
  5. Map root = new HashMap();
  6. root.put( "user" , "user" ); // pass in string
  7. //root.put( "product" , object.url()); //Input object (will report an error)
  8. try {
  9. Configuration cfg = new Configuration(new Version(2,3,0));
  10. cfg.setDefaultEncoding( "UTF-8" );
  11. //Set error message
  12. cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
  13. //Set error message
  14. cfg.setLogTemplateExceptions( true );
  15. out = new FileWriter(new File(destPath + "main.html" ));
  16. //Set the .ftl template file path
  17. cfg.setDirectoryForTemplateLoading(new File(destPath));
  18. //Set the name of the .ftl template file loaded by template
  19. Template temp = cfg.getTemplate( "main.ftl" );
  20. //Talk about data source and template generation.html file
  21. temp .process(root, out );
  22. out .flush();
  23. } catch (MalformedTemplateNameException e) {
  24.  
  25. } catch (IOException e) {
  26.  
  27. } catch (Exception e) {
  28.  
  29. }finally {
  30. try {
  31. if ( out != null )
  32. out . close ();
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. }

5. WebView loads main.html

  1. webview.post(new Runnable() {
  2. @Override
  3. public void run() {
  4. String templateDirRoot = getFilesDir().getAbsolutePath();
  5. String url = "file://" + templateDirRoot + "main.html" ;
  6. webview.loadUrl(url);
  7. }
  8. });

Problem points

1. Why do we need to convert mian.tpl into main.ftl file first, instead of putting the mian.ftl file directly into assets, and then directly load the main.ftl file in the template?

Because the files in assets cannot be read directly, you need to put the files in data/data/package/… before operating

2. Suddenly found that the 2016 version of freemarker cannot pass objects.

For example, in the main.ftl file, ${model.name} can no longer be converted to main.html, and the following error is prompted

  1. Unresolved exception class when finding catch block: java.beans.IntrospectionException

The official statement says it is possible, but I have tested it countless times and still cannot compile object transfer.

The name can be obtained as follows

  1. //activity.java
  2. User   user = new User ();
  3. user .setName= "Zhang San"  
  4. Map map = HashMap();
  5. map.put( "name" , user .getName());
  6.  
  7. //main.tpl
  8. <html>
  9. <body>
  10. ${ name }
  11. <body>
  12. <html>

The following method cannot obtain the name

  1. //activity.java
  2. User   user = new User ();
  3. user .setName= "Zhang San"  
  4. Map map = HashMap();
  5. map.put( "user" , user );
  6.  
  7. //main.tpl
  8. <html>
  9. <body>
  10. ${ user . name }
  11. <body>
  12. <html>

Summarize

***I didn't find that the webView page loading was much faster, maybe because the data volume was small. After all, it had to operate the SD card. The traffic was indeed saved, and there was less direct data interaction code between Java and HTML.

<<:  The six easiest programming languages ​​to learn for beginners

>>:  Regarding Android adaptation, it is enough to read this article

Recommend

6.18 is coming, how to make better use of coupons?

Merchants can freely set the functions and usage ...

@Everyone today, pay attention to this!

Today is the 15th day of the seventh lunar month,...

Is it worth it to have a 2K screen on your smartphone?

The pixels of smartphone screens have reached a l...

Tesla blames State Grid for new car failure, official apology: recording edited

On February 1, Tesla officially issued an apology...

Popcorn dropped from a roadside tree? Don’t eat it!

Now is the leaf-viewing season in southern my cou...

The Three Kingdoms’ annual drama: Lost on Journey: Xu Jiong!

Mixed Knowledge Specialized in treating misunders...

How much does it cost to develop a fast food app in Nagqu?

WeChat Mini Program is an application that users ...