首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我们可以使用NGINX作为模板引擎的webapp吗?

问我们可以使用NGINX作为模板引擎的webapp吗?
EN

Stack Overflow用户
提问于 2018-02-02 07:36:57
回答 2查看 4.5K关注 0票数 4

我需要基本的html模板for应用程序,如:

m2=John被调用,它应该返回text/html响应,如下所示:

代码语言:javascript
复制
<html>
<body>
    <p>Nice to see you John. Platform greets you "hello".</p>
</body>
</html>

名字和问候是从帕拉姆模版的。模板是这样的:

代码语言:javascript
复制
 <html>
 <body>
     <p>Nice to see you {{param1}}. Platform greets you "{{param2}}".</p>
 </body>
 </html>

我目前已经在使用express.js的节点服务器中这样做了,然后通过nginx.conf公开该服务器:

代码语言:javascript
复制
server {
    listen 80;
    # server_name example.com;

    location / {
        proxy_pass http://private_ip_address:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

我想知道,如果不将节点服务器托管在3000端口上,使用一些插件或使用裸nginx的其他配置,是否可以做到这一点。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-03-04 12:46:28

我能够解决这个问题,只使用Nginx来编程,使用OpenR陛下的lua模块。

https://github.com/openresty/lua-nginx-module提供了在nginx.conf中编程的能力,在那里人们可以使用现有的lua库(如https://github.com/bungle/lua-resty-template )来进行模板开发!

myapp.lua:

代码语言:javascript
复制
local template = require("resty.template")
local template_string = ngx.location.capture("/templates/greet.html")
template.render(template_string.body, {
    param1 = ngx.req.get_uri_args()["param1"],
    param2 = ngx.req.get_uri_args()["param2"]
})

greet.html:

代码语言:javascript
复制
<html>
<body>
     <p>Nice to see you {{param1}}. Platform greets you "{{param2}}".</p>
</body>
</html>

nginx.conf:

代码语言:javascript
复制
worker_processes  1;
error_log logs/error.log;
events {
    worker_connections 1024;
}
http {
    root ./;
    server {
        listen 8090;

    location /myapp {
        default_type text/html;
        content_by_lua_file ./lua/myapp.lua;
    }
}

content_by_lua_file是开放的力量来的地方。

我在这里描述了整个过程:https://yogin16.github.io/2018/03/04/nginx-template-engine/

希望有人会觉得这很有帮助。

票数 12
EN

Stack Overflow用户

发布于 2018-02-02 08:55:06

您不能用nginx渲染文件。

只需用nginx和重写指令发送文件,然后在文件中只包含一些javascript,用查询参数替换文本内容。

Nginx conf:

代码语言:javascript
复制
    location / {
        rewrite ^ /static/index.html break;
    }

index.html:

代码语言:javascript
复制
<div>My content <span id="name"></span></div>
<script>



function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

document.getElementById("name").textContent = getParameterByName("foo"):

</script>
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48577858

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档