简体   繁体   English

使用香草JavaScript的HTML模板

[英]HTML templating with vanilla JavaScript

I'm having a SharePoint app that retrieve page content from a library, and feeding both desktop and mobile sites. 我有一个SharePoint应用程序,该应用程序从库中检索页面内容,并同时为桌面和移动网站提供数据。 We also have links within the page, how can I render HTML templating with vanilla JavaScript? 页面中也有链接,如何使用香草JavaScript渲染HTML模板?

For example, we have couple on-page links from the page content: 例如,我们有来自页面内容的几个页面上链接:

<a class="template" href="/3.aspx">

I want to add either http://<sitename>/pages/ or http://<sitename>/pages/m/ infront of the href depends on the screen size or devices. 我想在href的前面添加http://<sitename>/pages/http://<sitename>/pages/m/取决于屏幕大小或设备。

How can I achieve that via vanilla JS ? 我如何通过vanilla JS实现呢?

Screen size way: 屏幕尺寸方式:

function isMobile() {
    return window.innerWidth < 800;
}

var mobileUrl = 'http://<sitename>/pages/m/1.html';
var desktopUrl = 'http://<sitename>/pages/index.html';
window.location = isMobile() ? mobileUrl : desktopUrl;

More elegant "duck type" mobile check 更优雅的“鸭式”移动支票

function isMobile() {
    return typeof window.orientation !== 'undefined';
}

Also there is a way to analyze navigator.userAgent value 也有一种分析navigator.userAgent值的方法

With a lightweight library called lit-html it's straightforward: 使用名为lit-html的轻量级库,它很简单:

import { html, render } from 'https://unpkg.com/lit-html/lit-html.js?module';

const linkTemplate = orientation =>
  html`<a href="https://<sitename>/pages/{orientation != null ? 'm/' : '/'}3.aspx">Link text</a>`

render(linkTemplate(window.orientation), container)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM