在python代码中使用变量代替html字体属性的值

时间:2018-07-29 01:37:18

标签: html variables fonts attributes python-3.6

实际上我必须将python3程序数据存储为html文件中的输出,为此,我想让用户设置html字体属性,或者可以说我想先在变量中存储html字体属性,然后使用这些变量在html的字体属性中。例如,这是在html中设置字体属性的常用方法:

<html>
<body>

<p><font face="verdana" color="green" size="3">This is some text!</font></p>

</body>
</html>

但是我想要这样的东西:

font_face = "verdana"
font_color = "green"
font_size = 3

<html>
<body>

<p><font face="font_face" color="font_color" size="font_size">This is some text!</font></p>

</body>
</html>

我在Google上搜索了很多以找到其解决方案,但找不到,现在我在这里问,希望有人能给出其解决方案。谢谢。

2 个答案:

答案 0 :(得分:0)

首先,如果您要呈现html,建议使用jinja2这样的模板框架。

但是,如果您想将文本输出为html并向其中插入值,则可能看起来像这样:

font_face = "verdana"
font_color = "green"
font_size = 3

html = """
<html>
<body>

<p><font face="{font_face}" color="{font_color}" size="{font_size}">This is some text!</font></p>

</body>
</html>
""".format(font_face=font_face, font_color=font_color, font_size=font_size)

这将为您提供一个包含要查找的html的字符串。

答案 1 :(得分:0)

您也可以将模板与python库一起使用,但是字符串格式看起来更好,并且不需要导入即可使用它们 很好笑,我整天都在研究Django,却忘了.format()

       <nav class="navbar" id="myNavbar">
            <div class=logoImg>
                <a class="resImg"><img class="active" src="images/logo.jpeg" height="64" width="173" /></a>
                <a href="javascript:void(0);" class="icon" onclick="myFunction()">&#9776;</a>
            </div>
            
            <div class="mainMenu">
                <a>option 1</a>
                <a>option 2</a>
                <a>option 3</a>
                <a>option 4</a>
                <a>option 5</a>
                <a>option 6</a>
                <a>option 7</a>
                <a>option 8</a>
            </div>
        </nav>
        
        <script>
            /*add the responsive class to the navbar when the user clicks on the bar button*/
            function myFunction()
            {
                var x = document.getElementById("myNavbar");
                if (x.className === "navbar")
                    {
                        x.className += " responsive";
                    }
                else
                    {
                        x.className = "navbar";
                    }
            }
        </script>